简体   繁体   English

给定数字的浮点分辨率

[英]Floating point resolution at a given number

I would like to know the epsilon of a floating point number around a given value. 我想知道给定值附近的浮点数的epsilon。

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. std::numeric_limits<floating_point_type>::epsilon()仅针对数字1.0提供此功能,而我希望函数可以对任何数字使用。

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 好吧,最简单的解决方案是在值的正上方找到epsilon(即,从该值到下一个可表示的值的距离)

std::nextafter(x, std::numeric_limits<floating_point_type>::infinity()) - x

Similarly to find the epsilon below the value, you could do 同样,要找到低于该值的epsilon,您可以

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. 请注意,如果x是2的幂,则这两个将不相同。

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). 现在,有一个轻微的警告有:以上所计算的小量FLT_MAX将是无穷大(可以说这是一种正确的答案但它并不完全符合IEEE-754的四舍五入规则)及以上的无限小量将为NaN(其中,好吧,我不知道我对此有何看法)。 In all other cases, the result will be exact. 在所有其他情况下,结果将是准确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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