kov*_*rex 15 c++ floating-point double
标题是不言自明的,输入给出双倍值,我想添加/减少可能的最小量.
GMa*_*ckG 23
如果你的编译器实现了C99的数学函数/ C++ 11,你可以使用nextafter:
#include <cfloat> // DBL_MAX
#include <cmath> // std::nextafter
double x = 0.1;
// next representable number after x in the direction of DBL_MAX
double xPlusSmallest = std::nextafter(x, DBL_MAX);
Run Code Online (Sandbox Code Playgroud)
即使你的编译器不支持它,它也可能有一个内在的东西.(_nextafter例如,MSVC 从2005年开始.GCC可能将其作为标准实施.)
如果您的编译器不支持它,但可以使用Boost,则可以执行以下操作:
#include <boost/math/special_functions/next.hpp> // boost::float_next
double x = 0.1;
// next representable number after x
double xPlusSmallest = boost::math::float_next(x);
Run Code Online (Sandbox Code Playgroud)
这相当于此(模拟C99):
#include <boost/math/special_functions/next.hpp> // boost::nextafter
#include <cfloat> // DBL_MAX
double x = 0.1;
// next representable number after x in the direction of DBL_MAX
double xPlusSmallest = boost::math::nextafter(x, DBL_MAX);
Run Code Online (Sandbox Code Playgroud)
如果这些都不适合你,你只需要打开Boost标头并复制它.
这是一个非常脏的技巧,实际上并不合法,只有在您的平台使用IEEE754浮点数时才有效:浮点数的二进制表示形式的顺序与浮点值相同,因此您可以增加二进制表示形式:
double x = 1.25;
uint64_t * const p = reinterpret_cast<uint64_t*>(&x);
++*p; // undefined behaviour! but it gets the next value
// now x has the next value
Run Code Online (Sandbox Code Playgroud)
通过通常的二元复制体操来获得适当的uint64_t价值,你可以完全合法地达到同样的效果.确保正确检查零,无穷大和NaN.