In C++, std::log10(x) is the base-10 logarithm. It tells you the power of ten that gives x. Since 103 is 1000, log10(1000) is 3.
This is the logarithm on a calculator with the log key. It is useful for counting digits, for decibels, for pH, and for earthquake scales. The input must be greater than zero.
std::log10() 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::log10. Start with these lines.
C++
double a = std::log10(1000.0); // double version
float b = std::log10(1000.0f); // float version
Call
What it does
std::log10(1000.0)
Passes a double and returns a double. Here the result is 3.
std::log10(1000.0f)
Passes a float, so the float overload runs and returns a float.
std::log10(100)
An integer is converted to double. Returns 2 as a double.
Write std::log10 so the C++ overloads for float, double, and long double are used.
Library declarations
C++
float log10(float x);
double log10(double x);
long double log10(long double x);
double log10(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 base-10 logarithm of x.
-inf
Returned when x is 0.
NaN
Returned when x is negative.
C++ Examples
Example 1 — Powers of Ten
Print the base-10 log of a few numbers. Exact powers of ten give whole numbers.
C++
#include <cmath>
#include <iostream>
int main() {
double values[] = {1.0, 10.0, 1000.0, 0.001, 50.0};
for (double v : values) {
std::cout << "log10(" << v << ") = " << std::log10(v) << '\n';
}
return 0;
}
The concentration is a tiny number, so cout prints it in scientific form, such as 1e-07.
log10(1e-7) is -7, and the minus sign in front of it makes the pH 7, which is neutral water.
1e-3 is more acidic with pH 3. The mixed value 3.2e-5 is not a power of ten, so its pH is the decimal 4.49485.
Frequently Asked Questions
std::log10(x) returns the base-10 logarithm of x. It is the power you raise 10 to in order to get x, so log10(1000.0) is 3.
The base-10 logarithm as float, double, or long double. log10(0) is -inf, and log10 of a negative number is NaN.
For a positive integer n, digits = floor(log10(n)) + 1. This does not work for 0, because log10(0) is -inf. Check for zero first, or divide by 10 in a loop.
log() is base e (the natural log), and log10() is base 10. log10(100) is 2, but log(100) is about 4.60517.
Include <cmath> and write std::log10(). That always works and picks the C++ overloads. The global name ::log10 often works too, but the standard does not promise it, and it may only take a double.