C ++ next float with numeric_limits / epsilon? [英] C++ next float with numeric_limits / epsilon?
问题描述
在C ++中考虑一个正常实数 TREAL x
(不是subnormal,不是NaN /无限)( TREAL
= float
, double
, long double
) >
以下是从浮点角度查找上一个和下一个 x
的好解决方案?
Consider a "normal" real number TREAL x
in C++ (not subnormal and not NaN/Infinite) (TREAL
= float
, double
, long double
)
Is the following the good solution to find the previous and next x
from a floating-point point of view ?
TREAL xprev = (((TREAL)(1.)) - std::numeric_limits<TREAL>::epsilon()) * x;
TREAL xnext = (((TREAL)(1.)) + std::numeric_limits<TREAL>::epsilon()) * x;
非常感谢。
推荐答案
C99和C ++ 11在< math.h>
和中有nextafter,nextafterl和nextafterf函数; cmath>
。使用基本算术和epsilon实现它们将是乏味的,因为您需要考虑四舍五入。使用二进制表示法可能更容易,但我不知道符号和幅度表示的效果和-0.0的存在(请参阅 Fred's回答需要什么)。
C99 and C++11 have nextafter, nextafterl and nextafterf functions in <math.h>
and <cmath>
. Implementing them with basic arithmetic and epsilon would be tedious as you'd need to take rounding into account. Working on the binary representation is probably easier, but I wonder about the effect of the sign and magnitude representation and the existence of -0.0 (see Fred's answer for what is needed).
这篇关于C ++ next float with numeric_limits / epsilon?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!