Calculate logarithm of a number in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { int x = 1000; double lg = log10(x); std::cout << lg << std::endl; // 3 return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { int x = 1000; double lg = log(x); std::cout << lg << std::endl; // 6.90776 return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { int x = 1000; double lg = log2(x); std::cout << lg << std::endl; // 9.96578 return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <cmath> int main() { int x = 1000; double lg = log10(x) / log10(2); std::cout << lg << std::endl; // 9.96578 lg = log2(x) / log2(2); std::cout << lg << std::endl; // 9.96578 return 0; } |
That’s all about calculating the logarithm of a number in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)