log2 Function

Calculates the base-2 logarithm of a double precision floating-point value.

Include

<math.h>

Prototype

double log2(double x);

Argument

x
any double precision floating-point positive number

Return Value

Returns the base-2 logarithm of x. -inf is returned if x is 0 and NaN is returned if x is a negative number.

Remarks

A domain error occurs for argument less than 0. A range error might occur if the argument is equal to zero.

Example

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

int main(void)
{
  double x, y;

  errno = 0;
  x = 2.0;
  y = log2(x);
  if(errno)
    perror("Error");
  printf("The base-2 logarithm of %f is %f\n", x, y);

  errno = 0;
  x = 0.0;
  y = log2(x);
  if(errno)
    perror("Error");
  printf("The base-2 logarithm of %f is %f\n", x, y);

  errno = 0;
  x = -2.0;
  y = log2(x);
  if(errno)
    perror("Error");
  printf("The base-2 logarithm of %f is %f\n", x, y);
}

Example Output

The base-2 logarithm of 2.000000 is 1.000000
The base-2 logarithm of 0.000000 is -inf
Error: domain error
The base-2 logarithm of -2.000000 is nan