English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ ilogb() function usage and example

C++ Library Function <cmath>

C ++The ilogb() function in uses FLT_RADIX as the base of the logarithm and returns the integer part of the logarithm of |x|.

This is<cmath>defined in the header file.

Mathematically

x = significand * FLT_RADIXexponent

significand is in [1.0,2.0) within the range of floating-point values, x is the parameter passed to ilogb(), and exponent is the integer value returned by ilogb(). The value of FLT_RADIX is generally2.

The value returned by ilogb() is greater thanfrexp()The exponent generated by the function is smaller than1 , because the number of significant digits is in [ 1.0,2.0] range, rather than frexp() in [0.5,1.0] range.

ilogb() prototype [from C ++ 11Standard beginning]

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

The ilogb() parameter

The ilogb() function accepts a parameter, whose ilogb is calculated.

The return value of ilogb()

The ilogb() function uses FLT_RADIX as the base of the logarithm and returns the integer part of the logarithm of |x|.

  • If the parameter is 0, it returns FP_LOGB0.

  • If the parameter is NaN, it returns FP_LOGBNAN.

  • If the parameter is infinite, it returns INT_MAX.

Example1:How the ilogb() function works in C ++How does it work in

#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 << "" * cout << " << FLT_RADIX << "^" << result << endl << endl;
    return 0;
}

When the program is run, the output is:

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

Example2:The ilogb() function with integer 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 << "" * cout << " << FLT_RADIX << "^" << result << endl << endl;
    
    return 0;
}

When the program is run, the output is:

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

C++ Library Function <cmath>