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;
Thank you very much.
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).