C++ std::log1p
In C++, std::log1p computes the natural logarithm of 1 + x. It preserves precision for small x, where adding x to 1 can lose significant digits.
A simple example
std::log1p
- Start with 0
- Do this Find the natural log of 1 + 0
- Result 0
#include <iostream>
#include <cmath>
int main() {
std::cout << (std::log1p(0.0)) << '\n';
}
0
Syntax
std::log1p(growth)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonConvert a small growth rate accurately
A dashboard measures a percentage change so small that rounding can hide it. Use a numerical operation designed for a change near zero to retain the information in the original reading.
#include <cmath>
#include <cstdio>
int main() {
const double growth = 0.01;
std::printf("%.3f\n", std::log1p(growth));
return 0;
}
0.010
A one-percent increase gives a continuous rate of about 0.00995033, displayed to three decimal places.
Convert a small loss
A test signal loses two percent of its level. The analyst converts a fractional change into its continuous log change.
Using -0.02 gives -0.0202 for this measurement.
Compare a small weekly increase
A greenhouse model records growth of half a percent. Its analyst uses the fractional increase directly to compute a stable log change.
Using 0.005 gives 0.0050 for this measurement.
What to watch for
Pass the increase itself. Adding one before the call changes the calculation.