如何查找最接近的下一个/前一个double值(numeric_limits :: epsilon给定数字) [英] How to find nearest next/previous double value (numeric_limits::epsilon for given number)
问题描述
标题是完全不说明的,输入是双值的,我想添加/减去最小的可能。 >
如果你的编译器实现了C99的数学函数/ C ++ 11,你可以使用 nextafter
:
#include< cfloat> // DBL_MAX
#include< cmath> // std :: nextafter
double x = 0.1;
//在DBL_MAX的方向上x后的可表示数字
double xPlusSmallest = std :: nextafter(x,DBL_MAX);
即使你的编译器不支持它,它可能有一个内在的。 (例如,MSVC自2005年以来已经有 _nextafter
)。
不支持它,但Boost可以使用,您可以这样做:
#include< boost / math / special_functions /next.hpp> // boost :: float_next
double x = 0.1;
//下一个可表示的数字x
double xPlusSmallest = boost :: math :: float_next(x);
这相当于这个(模拟C99):
#include< boost / math / special_functions / next.hpp> // boost :: nextafter
#include< cfloat> // DBL_MAX
double x = 0.1;
//在DBL_MAX方向的x后面的下一个可表示数字
double xPlusSmallest = boost :: math :: nextafter(x,DBL_MAX);
如果这些都不适合你,你只需要打开Boost标题,复制它。
The title is quite self-explanatory, input is given double value, and I want to add/substract the smallest amount possible.
If your compiler implements C99's math functions/C++11, you can use the 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);
Even if your compiler doesn't support it, it probably has an instrinsic for it. (MSVC has had _nextafter
since 2005, for example. GCC probably implements it as standard.)
If your compiler doesn't support it but Boost is available to you, you can do this:
#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);
Which is equivalent to this (emulating 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);
And if none of those work for you, you'll just have to crack open the Boost header and copy it.
这篇关于如何查找最接近的下一个/前一个double值(numeric_limits :: epsilon给定数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!