C++ cmath log2,log2f and log2l function

The C++ <cmath> log2mlog2f and log2l functions compute the base-2 logarithm of the parameter.The declaration of the functions are given below.

1 float log2(float x);
2 double log2(double x);
3 long double log2(long double x);
4 float log2f(float x);
5 long double log2l(long double x);

x -The value whose base-2 logarithm is to be computed.

Return type
floating point -Returns the base-2 logarithm of x.

Some point to note:

i) log2(x) is same log2(x).

ii) Domain error occur if argument is less than 0.

iii) Range error may occur if the argument is 0.

iv) If NAN is passed ‘nan’ is returned, if INFINITY is passed ‘inf’ is returned.

Code example

/*Passing floating point value*/
cout<< “log2(4)=” << log2(4) << endl;

/*Passing -ve<0 value */
cout<< “log2(-1)=” << log2(-1) << endl;

/*Passing 0 */
cout<< “log2(0)=” << log2(0) << endl;

/*Passing NAN */
cout<< “log2(NAN)=” << log2(NAN) << endl;

/*Passing INFINITY */
cout<< “log2(INFINITY)=” << log2(INFINITY) << endl;

Output (base on Code::Blocks)

log2(4)= 2
log2(-1)= nan
log2(0)= -inf
log2(NAN)= nan
log2(INFINITY)= inf


log1pf and log1pl


i)The 4th version log2f is same as the 1st version float log2(float).The ‘f‘ character stands for ‘float’ which signify the argument and return type of the function.

ii)The 5th version log2l is same as the 3rd version long double log2(long double).The ‘l‘ character stands for ‘long double’ which signify the argument and return type of the function.

Code example

#include <typeinfo>

/*log2f */
cout<< “*log2f\n”;
float f=2;
cout<< typeid( log2f(2) ).name() << endl /*identify type of log2f retunred value */
<< typeid( log2(f) ).name() << endl; /*identify type of log2(float) returned value */

cout<< “*log2l\n”;
long double ld=2;
cout<< typeid( log2l(2) ).name() << endl /*indentify type of log2l returned value */
<< typeid( log2(ld) ).name() << endl; /*identify type of log2(long double) returned value*/


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