C++ cmath acos , acosf and acosl function


The C++ <cmath> acos,acosf and acosl function compute the arc cosine of the given value.All the variant of acos function provided by C++ is given below:

1 float acos(float x);
2 double acos(double x);
3 long double acos(long double x);
4 float acosf(float x);
5 long double acosl(long double x)

Some points to note:

i-The argument ‘x’ should be in the interval [-1,1].If the argument is not in the said interval a domain error occurs and so ‘nan‘ is returned.

ii-The returned value is in the interval [0,π] radians.

iii-The second version is the default version that is called when acos is called in our program.

iv-When the argument passed is int type the default version is called.

Note arc cosine means inverse of cos,so acos(x) is same as cos^-1(x) .

Link: C++ nan

Code example

#include <typeinfo>

cout<< acos(0.12) << endl
<< acos(1);

cout<< typeid( acos(0.12) ).name( ) ;

Output

1.45051
0
d (means ‘double’)

Here is another code example that check the return value when the argument does not belong to the specified interval.

cout<< acos(1.1) << endl
<< acos(-2) ;

Output

nan
nan



acosf and acosl

acosf function

The acosf function is same as the 1st function-float acos(float).The ‘f’ appended to acos in acosf stands for float,it signify the type of the argument and the return value.

Code example

float f=0.2;

cout<< acos(f) << endl
<< acosf(0.2) << endl ;

cout<< typeid( acos(f) ).name( ) << endl
<< typeid( acosf(0.2) ).name( ) << endl ;

cout<< acosf(2.3) ;

Output

1.36944
1.36944
f
f
nan

You can see that the return type is float in asinf and asin(float).

acosl function

The 3rd version-long double acos(long double),is similar to acosl function.The ‘l’ signify the type long double of the argument and the return value.

Code example

long double ld=0.22 ;

cout<< acos(ld) << endl
<< acosl(0.22) << endl ;

cout<< typeid( acos(ld) ).name( ) << endl
<< typeid( acosl(0.22) ).name( ) << endl ;

cout<< acosl(2.3) ;

Output

1.34898
1.34898
e (means ‘long double’)
e (means ‘long double’)
nan


 


Getting degree instead of radian with acos

Since the value obtained in computing the acos function is in radian,we will apply simple conversion rule to get the value in degree.

Now,

1 radian = (180/3.141592) degree

So multiplying the output value with (180/3.141592) will change the value to degree type.

Code example

cout<< “acos(0.5)=” << ( acos(0.5)*180 )/3.141592 << “°” << endl ;

Output

acos(0.5)=60°

That was easy,wasn’t it?