Sunday, 11 March 2012

The frexp Function in C & C++


More functions from the  <math.h> or <cmath> header files. Today it’s about the frexp function.

Given a floating point value a, the function returns S and n such that a = S x 2n.

The value of S is limited to a range of greater than or equal to 0.5 and less than 1.

The value of n is an integer and is returned by way of a pointer.

From C11 standard.





Test Code.

I tested the functions in Visual C++ 2010 as an console application.

// The standard library includes the system function.
#include <cstdlib>

// C++ standard I/O library.
#include <cstdio>

// C++ math library.
#include <cmath>

int main()
{

     // Header.
     printf("The frexp Function in C & C++\n\n");
     printf("Given a, the function returns S and n\n");
     printf("such that a  = S x 2 to the nth power.\n\n");

     // Counter for loop.
     int i;
     // Return value, significant.
     double S;
     // Arugment.
     double a;
     // 2 to the Nth power.
     int n = 0;

     printf("a     =   S   x 2 ^ n\n\n");
     for (i = 10; i < 27; ++i)
     {
           a = i / 10.0;
           S = frexp(a, &n);
           printf ("%4.3f = %4.3f x 2 ^ %d\n", a, S, n);
     }

     // Keep console window open.
     system("pause");

     // Return some value.
     return 0;
} // end main
 
Output.



No comments:

Post a Comment