gpt4 book ai didi

c++ - 如何找到最近的下一个/上一个 double 值(numeric_limits::epsilon 对于给定的数字)

转载 作者:IT老高 更新时间:2023-10-28 22:26:13 26 4
gpt4 key购买 nike

标题是不言自明的,输入是 double 值,我想加/减尽可能少的数量。

最佳答案

您可以使用 nextafter,如果您的编译器实现了 C99 的数学函数(即 C++11 及更高版本),则可以使用该功能。这个函数(及其各种重载)可以描述为:

double nextafter(double value, double target);

它将从 value target 方向移动尽可能小的量(通常通过调整 float 的位表示) .如果 value 已经在 target 处,则什么也不做。

如果target 大于value,这将增加value 的最小量。如果 target 小于 value 这将减少 value 的最小量。

常见的用法是传递 DBL_MAXINFINITY 作为目标以增加最小数量(或否定它们以减少最小数量)。

DBL_MAXINFINITY 之间的选择取决于您要在边界处执行的操作 - 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 头文件并复制它。

关于c++ - 如何找到最近的下一个/上一个 double 值(numeric_limits::epsilon 对于给定的数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10160079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com