log2() Function with Example in C++

C++ log2() function: Here, we are going to learn about the log2() function with example of cmath header in C++ programming language.
Submitted by IncludeHelp, on May 20, 2020

C++ log2() function

log2() function is a library function of cmath header, it is used to get the binary logarithm (the base-2 logarithm) of the given value. It accepts a value (float, double, or long double) and returns the binary logarithm.

Syntax of log2() function:

C++11:

     double log2 (double x);
      float log2 (float x);
long double log2 (long double x);
     double log2 (T x);

Parameter(s):

  • x – represents the value whose binary logarithm to be found.

Return value:

It returns the binary logarithm of the given value x.

Note:

  • If the given value is negative, it causes a domain error.
  • If the given value is zero, it may cause a pole error.

Example:

    Input:
    float x = 2.0f
    
    Function call:
    log2(x);
    
    Output:
    1

C++ code to demonstrate the example of log2() function

// C++ code to demonstrate the example of
// log2() function

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    float x = 0.0f;

    x = 10.0f;
    cout << "log2(" << x << "): " << log2(x) << endl;

    x = 2.0f;
    cout << "log2(" << x << "): " << log2(x) << endl;

    x = 20.0f;
    cout << "log2(" << x << "): " << log2(x) << endl;

    x = -10.4f;
    cout << "log2(" << x << "): " << log2(x) << endl;

    x = 0.0f;
    cout << "log2(" << x << "): " << log2(x) << endl;

    x = 100.6f;
    cout << "log2(" << x << "): " << log2(x) << endl;

    return 0;
}

Output

log2(10): 3.32193
log2(2): 1
log2(20): 4.32193
log2(-10.4): nan
log2(0): -inf
log2(100.6): 6.65249

Reference: C++ log2() function




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.