This post will discuss how to calculate the logarithm of a number in C++.

The header <cmath> provides a several common logarithmic functions in C++. This post provides an overview of some of the commonly used functions.

1. Using log10() function

The log10() function returns the base-10 logarithm of the specified number. It takes a floating-point value whose logarithm is calculated and calculates the common logarithm of it. C++11 offers additional overloads for integral types, which effectively cast the argument to a double. It can be used as follows:

Download  Run Code

2. Using log() function

The log() function returns the natural (base-e) logarithm of the specified number, which is the inverse of the natural exponential function. Its usage is demonstrated below:

Download  Run Code

3. Using log2() function

If you need the binary (base-2) logarithm of the specified number, consider using the log2() function. You can invoke it like this:

Download  Run Code

 
Alternatively, you can use the logarithmic identity to calculate the base-2 logarithm of a value. The logarithmic identity is logba = logy(a)/logy(b), therefore, log2n = logy(n)/logy(2), where y can be anything (10 or 2). Here’s the working example:

Download  Run Code

That’s all about calculating the logarithm of a number in C++.