C++ ilogb()

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

This is defined in <cmath> header file.

Mathematically,

x = significand * FLT_RADIXexponent

significand is a floating point value in the range [1.0, 2.0), x is the argument passed to ilogb() and exponent is the integer value returned by ilogb(). The value of FLT_RADIX is generally 2.

The value returned by ilogb() is one less than the exponent generated by the frexp() function, since the significand is in the range [1.0, 2.0) instead of [0.5, 1.0) as in frexp().


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

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

ilogb() Parameters

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


ilogb() Return value

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

  • If the argument is 0, it returns FP_LOGB0.
  • If the argument is NaN, it returns FP_LOGBNAN.
  • If the argument is infinite, it returns INT_MAX.

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

#include <iostream>
#include <cmath>
#include <cfloat>

using namespace std;

int main()
{
	int result;
	double significand;
	double x = 16.81;

	result = ilogb(x);
	significand = x / pow(FLT_RADIX, result);

	cout << "ilogb (" << x << ") = " << result << endl;
	cout << x << " = " << significand << " * " << FLT_RADIX << "^" << result << endl << endl;

	return 0;
}

When you run the program, the output will be:

ilogb (16.81) = 4
16.81 = 1.05062 * 2^4

Example 2: ilogb() function with integral type

#include <iostream>
#include <cmath>
#include <cfloat>

using namespace std;

int main()
{
	int result, x = 19;

	result = ilogb(x);
	double significand = x/pow(FLT_RADIX,result);

	cout << "ilogb (" << x << ") = " << result << endl;
	cout << x << " = " << significand << " * " << FLT_RADIX << "^" << result << endl << endl;
	
	return 0;
}

When you run the program, the output will be:

ilogb (19) = 4
19 = 1.1875 * 2^4