The log2 function in C computes the base-2 logarithm of x
. A domain error occurs if the argument is less than zero. A pole error may occur if the argument is zero. The x
is the argument that is passed into the log2().
It is declared in math.h
and takes one argument in the form of double and returns the value of type double.
Syntax of log2 function in C:
//Syntax of log2 double log2(double x);
Parameters:
x
=> floating types (double)
Return value:
The log function return log2(x).
You can use the log2f() function to work specifically with float and log2l() to work with long double type. See the below syntax.
//Other log2 function in C float log2f(float x); long double log2l(long double x);
C program to understand the working of log2 function:
Below mentioned C example code shows the usage of log2().
Example 1:
#include <stdio.h> #include <math.h> int main() { double x = 4.2, result; result = log2(x); printf("log2(%lf) = %lf", x, result); return 0; }
Output:
log2(4.200000) = 2.070389
Example 2:
#include <stdio.h> #include <math.h> int main() { double x = 2, result; result = log2(x); printf("log2(%lf) = %lf", x, result); return 0; }
Output:
log2(2) = 1.000000
Error handling
- Errors are reported as specified in math_errhandling.
- Domain error occurs if arg is less than zero.
- Pole error may occur if arg is zero.
If the implementation supports IEEE floating-point arithmetic (IEC 60559),
- If the argument is ±0, -∞ is returned and FE_DIVBYZERO is raised..
- If the argument is 1, +0 is returned.
- If the argument is negative, NaN is returned and FE_INVALID is raised.
- If the argument is +∞, +∞ is returned.
- If the argument is NaN, NaN is returned.
#include <stdio.h> #include <math.h> #include <float.h> #include <errno.h> #include <fenv.h> #pragma STDC FENV_ACCESS ON int main() { // special values printf("log2(1) = %f\n", log2(1)); printf("log2(+Inf) = %f\n", log2(INFINITY)); //error handling errno = 0; feclearexcept(FE_ALL_EXCEPT); printf("log2(0) = %f\n", log2(0)); if(errno == ERANGE) { perror("errno == ERANGE"); } if(fetestexcept(FE_DIVBYZERO)) { puts("FE_DIVBYZERO raised"); } return 0; }
Output:
log2(1) = 0.000000
log2(+Inf) = inf
log2(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised
Recommended Post:
- Use of log10 function in C
- log function in C
- fabs use in C language
- abs labs llabs functions in C/C++
- floor function in C with example code.
- ceil function use in C programming.
- Use of pow function in C language.
- C program to calculate the power of a number.
- sqrt function in C.
- C program to find all roots of a quadratic equation using switch case.
- C program to find the roots of a quadratic equation.
- How to find whether a given number is prime number in C?
- Use of isxdigit in C programming.
- How to use ispunct function in C programming?