C programming ldexp,ldexpf and ldexpl math.h


In C programming the <math.h> ldexp, ldexpf and ldexpl function multiply the floating point number(the first parameter) with the integral power of 2.The declaration for the functions are given below.

1 float ldexp(float x, int exp);
2 double ldexp(double x, int exp);
3 long double ldexp(long double x, int exp);
4 long double ldexpf(float x, int exp);
5 long double ldexpl(long double x, int exp);

Parameters:
x – A floating point number.

exp -The value which will be raised as the power to 2.

Return type
floating point -Returns x multiplied by 2 to the power exp.

All the functions are the same,they compute the value ‘x*2exp‘.The 1st,2nd and the 3rd function have the same name i.e.’ldexp’.The 4th and 5th function have different names.What does having a different names mean is explained in detail below.

Some points to note:

i) ldexp(x,exp) is same as x * 2exp.

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

Code example

double d=9 ;

float f=9 ;

long double ld=9 ;

int exp=5 ;

printf(“%lf”, ldexp( d , exp ) ) ; //calls the 2nd version
printf(“\n%f”, ldexp( f ,exp ) ) ; //calls the 1st version
printf(“\n%Lf”, ldexp( ld , exp) ) ;//calls the 3rd version

printf(“\n%lf”, ldexp( NAN , exp) ) ;
printf(“\n%lf”, ldexp( INFINITY , exp ) ) ;

Output in Visual Studio,

288.000000
288.000000
288.000000
-nan(ind)
inf

The returned value for ‘NAN'(macro for NaN value), ‘-nan(ind)’means the value is not representable.






ldexpf

The ‘ldexpf‘ function is same as the 1st function.This means the parameter and return type of the function is float type.The ‘f‘ character appended to ‘ldexpf‘ stands for float and it signify the parameter and return type of the function.

Code example

float x=400 ;

int exp=2 ;

printf(“%f”, ldexp( x ,exp ) ); //Calls the 1st version
printf(“\n%f”, ldexpf( 400 ,exp ) ); Calls the 4th version

Output,

1600.000000
1600.000000


ldexpl

The ‘ldexpl‘ function is same as the 1st function.This means the parameter and return type of the function is float type.The ‘l‘ character appended to ‘ldexpl‘ stands for float and it signify the parameter and return type of the function.

Code example

long double x=400 ;

int exp=2 ;

printf(“%Lf”, ldexp( x ,exp ) ); //Calls the 3rd version
printf(“\n%Lf”, ldexpl( 400 ,exp ) ); Calls the 5th version

Output,

1600.000000
1600.000000