C++ std::nextafter
Move to the next representable floating-point value toward negative infinity.
A simple example
std::nextafter
- Start with 1.0
- Do this Take one double-precision step downward
- Result 0.9999999999999999
#include <iostream>
#include <cmath>
#include <iomanip>
int main() {
std::cout << std::setprecision(17) << (std::nextafter(1.0, 0.0)) << '\n';
}
0.99999999999999989
Syntax
std::nextafter(1.0, -INFINITY) < 1.0
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
./lessonTest just below a measurement limit
A calibration routine needs to test the nearest representable value on one side of a limit. Move by one floating-point step so the boundary test uses a value the computer can actually store.
#include <iostream>
#include <cmath>
int main() {
std::cout << ((std::nextafter(1.0, -INFINITY) < 1.0) ? "yes" : "no") << "\n";
return 0;
}
yes
The next representable value below one passes the strict less-than check.
Test the scale just below 2
A scale switches display ranges at 2. The tester needs the nearest representable double below this threshold to exercise the boundary.
There is no intervening double between the threshold and this result.
Test the exposure meter just below 8
A exposure meter switches display ranges at 8. The tester needs the nearest representable double below this threshold to exercise the boundary.
There is no intervening double between the threshold and this result.
What to watch for
The gap below a power of two can differ from the gap above it.