简体   繁体   中英

Floating point resolution at a given number

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM