且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何查找最接近的下一个/前一个double值(numeric_limits :: epsilon给定数字)

更新时间:2023-02-11 07:59:24

标题是完全不说明的,输入是双值的,我想添加/减去最小的可能。 >

如果你的编译器实现了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.