C library - frexp() function



The C library double frexp(double x, int *exponent) function return value is the mantissa, and the integer pointed to by exponent is the exponent. The resultant value is x = mantissa * 2 ^ exponent.

Mantissa is a part of logarithm that use after the decimal point.

Syntax

Following is the syntax of the C library function frexp()

double frexp(double x, int *exponent)

Parameters

This function accepts two parameters −

  • x − This is the floating point value to be computed.

  • exponent − This is the pointer to an int object where the value of the exponent is to be stored.

Return Value

This function returns the normalized fraction. If the argument x is not zero, the normalized fraction is x times a power of two, and its absolute value is always in the range 1/2 (inclusive) to 1 (exclusive). If x is zero, then the normalized fraction is zero and zero is stored in exp.

Example 1

Following is the C library that demonstrate the usage of frexp() function.

#include <stdio.h>
#include <math.h>

int main () {
   double x = 1024, fraction;
   int e;
   
   fraction = frexp(x, &e);
   printf("x = %.2lf = %.2lf * 2^%d\n", x, fraction, e);
   
   return(0);
}

Output

The above code produces following result −

x = 1024.00 = 0.50 * 2^11

Example 2

In this program, we extract the mantissa and exponent from a double precision number using frexp().

#include <stdio.h>
#include <math.h>

int main() {
   double num = 1234.5678;
   int exponent;

   // Extract mantissa and exponent
   double mantissa = frexp(num, &exponent);

   printf("Number: %.4lf\n", num);
   printf("Mantissa: %.4lf\n", mantissa);
   printf("Exponent: %d\n", exponent);

   return 0;
}

Output

On execution of above code, we get the following result −

Number: 1234.5678
Mantissa: 0.6028
Exponent: 11

Example 3

The program define the custom function my_exp() to get the calculation of approximate e^x using mantissa and exponent.

#include <stdio.h>
#include <math.h>

double my_exp(double x) {
   int exponent;
   double mantissa = frexp(x, &exponent);
   
   return ldexp(mantissa, exponent);
}

int main() {
   double x = 2.0;
   double approx_exp = my_exp(x);
   printf("Approximation of e^%.2lf = %.6lf\n", x, approx_exp);
   return 0;
}

Output

After executing the code, we get the following result −

Approximation of e^2.00 = 2.000000
Advertisements