![The C Standard Library Reference](/c_standard_library/images/c-mini-logo.jpg)
- The C Standard Library
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Standard Library Resources
- C Library - Quick Guide
- C Library - Useful Resources
- C Library - Discussion
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C library - ldexp() function
The C library ldexp() function of type double accepts two parameters say(x and exponent) which returns the result in the form of x multiplied by 2 raised to the power of exponent.
Syntax
Following is the syntax of the C library ldexp() function −
double ldexp(double x, int exponent)
Parameters
This function accepts two parameters −
x − This is the floating point value representing the significand.
exponent − This is the value of the exponent.
Return Value
This function returns x * 2 exp.
Example 1
Following is the basic C library program to see the illustration of ldexp() function.
#include <stdio.h> #include <math.h> int main () { double x, ret; int n; x = 0.65; n = 3; ret = ldexp(x ,n); printf("%f * 2^%d = %f\n", x, n, ret); return(0); }
Output
The above code produces the following result−
0.650000 * 2^3 = 5.200000
Example 2
Below the program calculate the volume of a sphere using mantissa and exponent.
#include <stdio.h> #include <math.h> double sphere_volume(double radius) { int expo; double mantissa = frexp(radius, &expo); // Calculate volume = (4/3) * π * (mantissa * 2^exponent)^3 double vol = (4.0 / 3.0) * M_PI * pow(ldexp(mantissa, expo), 3); return vol; } int main() { double sphere_radius = 5.0; double sphere_vol = sphere_volume(sphere_radius); printf("Volume of sphere with radius %.2lf = %.6lf\n", sphere_radius, sphere_vol); return 0; }
Output
On execution of above code, we get the following result −
Volume of sphere with radius 5.00 = 523.598776
Example 3
To get the approximate value of 2x can use two function − frexp() that return the value of mantissa and for returning the result has used ldexp().
#include <stdio.h> #include <math.h> double my_power_of_two(double x) { int expo; double mantis = frexp(x, &expo); return ldexp(mantis, expo); } int main() { double x = 3.96; double approx_power_of_two = my_power_of_two(x); printf("Approximate 2^%.2lf = %.6lf\n", x, approx_power_of_two); return 0; }
Output
After executing the above code, we get the following result −
Approximate 2^3.96 = 3.960000