Previous Page
Next Page

log2

Calculates the logarithm to base 2 of a number

#include <math.h>
double log2 ( double x  );
float log2f ( float x  );         (C99)
long double log2l ( long double x  );         (C99)

The base-2 logarithm of a number x is defined only for positive values of x. If x is negative, a domain error occurs; if x is zero, and depending on the implementation, a range error may occur.

Example

double x[ ] = { 0, 0.7, 1.8, 1234, INFINITY };

for ( int i = 0; i < sizeof( x ) / sizeof( double ); i++ )
{
  errno = 0;
  printf( "The base 2 log of  %.1f is %.3f.\n", x[i], log2( x[i] ) );
  if ( errno == EDOM || errno == ERANGE )
    perror( _  _FILE_  _ );
}

This code produces the following output:

The base 2 log of  0.0 is -inf.
log2.c: Numerical result out of range
The base 2 log of  0.7 is -0.515.
The base 2 log of  1.8 is 0.848.
The base 2 log of  1234.0 is 10.269.
The base 2 log of  inf is inf.

See Also

log( ), log10( ), log1p( ), exp( ), pow( )


Previous Page
Next Page