Unlock the Power of Logarithms in C++
Getting Started with the log2() Function
The log2() function, defined in the <cmath>
header file, is a powerful tool in C++ that allows you to calculate the base-2 logarithm of a number. This function has been a part of the C++ standard since C++11.
Understanding log2() Parameters
The log2() function takes a single mandatory argument, which must be a non-negative number (in the range [0, ∞]). If you try to pass a value less than zero, the function will return NaN (Not a Number).
Unraveling the log2() Return Value
So, what does the log2() function actually return? The answer is simple: it returns the base-2 logarithm of the input number. But what does this mean in practice?
Putting log2() to the Test
Let’s take a look at an example to see how the log2() function works in action:
“`cpp
include
include
int main() {
double num = 16.0;
double result = log2(num);
std::cout << “The base-2 logarithm of ” << num << ” is ” << result << std::endl;
return 0;
}
When you run this program, the output will be:
The base-2 logarithm of 16 is 4
“`
Exploring log2() with Integral Types
But what happens when we use the log2() function with integral types, such as integers? Let’s find out:
“`cpp
include
include
int main() {
int num = 16;
double result = log2(num);
std::cout << “The base-2 logarithm of ” << num << ” is ” << result << std::endl;
return 0;
}
When you run this program, the output will be:
The base-2 logarithm of 16 is 4
“`
Discover More
Want to learn more about logarithmic functions in C++? Check out our guides on:
- C++ log(): Calculate the natural logarithm of a number
- C++ log10(): Calculate the base-10 logarithm of a number