C++ logb()

The logb() function in C++ returns the logarithm of |x|, using FLT_RADIX as base for the logarithm.

Generally, FLT_RADIX is 2, so logb() is equivalent to log2() for positive values.

The function is defined in <cmath> header file.


logb() prototype [As of C++ 11 standard]

double logb (double x);
float logb (float x);
long double logb (long double x);
double logb (T x); // For integral type

The logb() function takes a single argument and returns a value of type double, float or long double.


logb() Parameters

The ilogb() function takes a single argument whose logb is computed.


logb() Return value

The logb() function returns the logarithm of |x|, using FLT_RADIX as base for the logarithm.

If x is zero it may cause a domain error or a pole error or no error, depending on the library implementation.


Example 1: How logb() function works in C++?

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	double x = 121.056, result;

	result = logb(x);
	cout << "logb(" << x << ") = " << "log(|" << x << "|) = "<< result << endl;

	return 0;
}

When you run the program, the output will be:

logb(121.056) = log(|121.056|) = 6

Example 2: logb() function with integral type

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	double result;
	int x = -5;

	result = logb (x);
	cout << "logb(" << x << ") = " << "log(|" << x << "|) = "<< result << endl;

	return 0;
}

When you run the program, the output will be:

logb(-5) = log(|-5|) = 2