In C++, std::log(x) is the natural logarithm, which uses the number e (about 2.71828) as its base. It answers this question: to what power must e be raised to get x? For x = 1 the answer is 0.
The function is the opposite of std::exp(). Be careful with the name: in C++ log() is base e, not base 10. For base 10 use std::log10(), and for base 2 use std::log2(). The input must be greater than zero.
std::log() is declared in <cmath> and is part of the group Exponential and logarithm. Exponentials and logarithms undo each other. A logarithm of zero is -inf, and a logarithm of a negative number is NaN.
Syntax
Include <cmath> and call std::log. Start with these lines.
C++
double a = std::log(10.0); // double version
float b = std::log(10.0f); // float version
Call
What it does
std::log(10.0)
Passes a double and returns a double. Here the result is 2.30259.
std::log(10.0f)
Passes a float, so the float overload runs and returns a float.
std::log(1)
An integer is converted to double. Returns 0 as a double.
Write std::log so the C++ overloads for float, double, and long double are used.
Library declarations
C++
float log(float x);
double log(double x);
long double log(long double x);
double log(Integer x); // for integer types
Parameters
Parameter
Description
x
Required. A positive number. Zero and negative numbers are outside the domain. An integer is converted to double.
Return Value
Return Value
Description
Logarithm
The natural logarithm of x.
-inf
Returned when x is 0. This is a pole error.
NaN
Returned when x is negative. This is a domain error.
C++ Examples
Example 1 — Common Values of log()
Print the natural log of a few numbers, including e itself.
C++
#include <cmath>
#include <iostream>
int main() {
double e = std::exp(1.0);
double values[] = {1.0, e, 10.0, 0.5};
for (double v : values) {
std::cout << "log(" << v << ") = " << std::log(v) << '\n';
}
return 0;
}
Dividing two natural logs converts the base. log(1000) / log(2) is the base-2 logarithm of 1000.
The value is 9.96578, so after about ten halvings 1000 drops to 1 or below.
std::ceil() rounds up to the next whole step, 10. This is the idea behind binary search taking about log2(n) steps.
Frequently Asked Questions
std::log(x) returns the natural logarithm of x. That is the power you must raise e to in order to get x, so log(1.0) is 0.
The natural logarithm of x as float, double, or long double. log(0) is -inf, and log of a negative number is NaN.
It is base e (the natural logarithm). Use std::log10() for base 10 and std::log2() for base 2. This is different from a calculator, where "log" often means base 10.
Divide two natural logs: log(x) / log(base). For example, std::log(81.0) / std::log(3.0) is 4. For base 2 and base 10, the dedicated functions are more exact.
Include <cmath> and write std::log(). That always works and picks the C++ overloads. The global name ::log often works too, but the standard does not promise it, and it may only take a double.