There is FLT_MIN
constant that is nearest to zero. How to get nearest to some number
value?
As an example:
float nearest_to_1000 = 1000.0f + epsilon;
// epsilon must be the smallest value satisfying condition:
// nearest_to_1000 > 1000.0f
I would prefer numeric formula without using special functions.
Caution: Bugs were found in this code while working on another answer. I hope to update this later. In the meantime, it fails for some values involving subnormals.
C provides a function for this, in the
<math.h>
header.nextafterf(x, INFINITY)
is the next representable value afterx
, in the direction towardINFINITY
.However, if you'd prefer to do it yourself:
The following returns the epsilon you seek, for single precision (float), assuming IEEE 754.
The following returns the next value representable in float after the value it is passed (treating -0 and +0 as the same).