Reputation: 1764
I would like to know the epsilon of a floating point number around a given value.
std::numeric_limits<floating_point_type>::epsilon()
provides that only for the number 1.0, while I would like a function to work on any number.
Is there any standard library solution to this? If not - how should I implement the function?
Upvotes: 1
Views: 238
Reputation: 41474
Well, the easiest solution to find the epsilon immediately above the value (that is, the distance from that value to the next representable value) would just be
std::nextafter(x, std::numeric_limits<floating_point_type>::infinity()) - x
Similarly to find the epsilon below the value, you could do
x - std::nextafter(x, -std::numeric_limits<floating_point_type>::infinity())
Note that those two won't be the same if x is an exact power of two.
Now, there is one slight caveat there: the calculated epsilon above FLT_MAX
will be infinity (arguably that's kind of the correct answer, but it doesn't quite match IEEE-754's rounding rules) and the epsilon above infinity will be NaN (which, well, I don't know how I feel about that). In all other cases, the result will be exact.
Upvotes: 5