C++ cmath cos , cosf and cosl function


The C++ <cmath> cos,cosf and cosl function compute the cosine of the given value.The declaration of the functions are given below.

1 float cos(float x);
2 double cos(double x);
3 long double cos(long double x)
4 float cosf(float x);
5 long double cosl(long double x);

Some points to note:

i-The argument ‘x‘ is measured in radian.

ii-The default version called is the cos function with double as argument and return type(the second version).

Code example

#include <typeinfo>

cout<< cos(98) << endl ; //calculate cosine of 98

cout<< typeid( cos(98) ).name() ; //verifying the type of cos(98) evaluated value

Output

-0.819288
d (means ‘double’)

The second version is always called.



cosf and cosl

cosf function

The cosf function version is same as the float cos(float) version.The character ‘f‘ appended to cos signify the type of the parameter or the return value or both,which of course stands for float.

Code example

#include <typeinfo>

float f=9;

cout<< cos(f) << endl ///calls the 1st version
<< cosf(9) ;

cout<< endl ;

cout<< typeid( cos(f) ).name() << endl
<< typeid( cosf(9) ).name() ;

Output

-0.911130
-0.911130
f
f

cosl function

The cosl function is same as the cos version with long double as the parameter type and return type(the 3rd version).The character ‘l‘ after cos stands for long double.

Code example

#include <typeinfo>

long double ld=90 ;

cout<< cos(ld) << endl
<< cosl(90) << endl ;

cout<< typeid( cos(ld) ).name() << endl
<< typeid( cosl(90) ).name() ;

Output

-0.448073
-0.448073
e (means ‘long double’)
e (means ‘long double’)





Making cos compute any value in degree

The argument passed to cos function is measured in radian.To make the cos function compute for degree type value,the degree should be first converted to radian type.Since cos accept only radian type conversion from degree to radian type is necessary.

The relation between radian and degree is shown below,

1 degree =(π/180) radian

Multiplying the argument with (3.141592/180) and computing the cos of the value will give the cosine of the given degree.

Code example

double degree=45;

cout<< “cos(45°)=” << cos( (degree*3.141592)/180 );

Output

cos(45°)=0.707107