您可以使用nextafter,如果您的编译器实现了 C99 的数学函数(即 C++11 及更高版本),则可以使用它。这个函数(及其各种重载)可以描述为:
double nextafter(double value, double target);
它将从value 向 target 移动尽可能小的量(通常通过调整浮点数的位表示)。如果value 已经在target,则什么都不做。
如果target 大于value,这将增加value 的最小量。如果target 小于value,这将减少value 的最小量。
常见的用法是传递DBL_MAX 或INFINITY 作为目标以增加最小数量(或否定它们以减少最小数量)。
DBL_MAX 和 INFINITY 之间的选择取决于你想在边界上做什么 - nextafter(DBL_MAX, DBL_MAX) == DBL_MAX,但nextafter(DBL_MAX, INFINITY) == INFINITY。
是的,它的名字很糟糕。另见nextafter and nexttoward: why this particular interface?。
#include <cfloat> // DBL_MAX
#include <cmath> // std::nextafter
double x = 0.1;
// Next representable number **after** x in the direction of DBL_MAX.
// (i.e., this is larger than x, and there is no double between it and x)
double xPlusSmallest = std::nextafter(x, DBL_MAX);
// Next representable number **before** x in the direction of -DBL_MAX.
// (i.e., this is smaller than x, and there is no double between it and x)
double xMinusSmallest = std::nextafter(x, -DBL_MAX);
即使你的编译器不支持它,它也可能有它的内在特性。 (例如,MSVC 自 2005 年以来就拥有 _nextafter。GCC 可能将其作为标准实现。)
如果您的编译器不支持它,但您可以使用 Boost,您可以这样做:
#include <boost/math/special_functions/next.hpp>
#include <cfloat>
double x = 0.1;
double xPlusSmallest = boost::math::nextafter(x, DBL_MAX);
double xMinusSmallest = boost::math::nextafter(x, -DBL_MAX);
如果这些都不适合你,你只需要打开 Boost 头文件并复制它。