问题描述
用 a_float == b_float
之类的东西比较两个浮点数是在找麻烦,因为 a_float/3.0 * 3.0
可能不等于 a_float代码> 由于舍入错误.
Comparing two floating point number by something like a_float == b_float
is looking for trouble since a_float / 3.0 * 3.0
might not be equal to a_float
due to round off error.
通常的做法是 fabs(a_float - b_float) <tol
.
如何计算tol
?
理想情况下,容差应该刚好大于一两个最低有效数字的值.因此,如果使用单精度浮点数 tol = 10E-6
应该是正确的.然而,这不适用于 a_float
可能非常小或可能非常大的一般情况.
Ideally tolerance should be just larger than the value of one or two of the least significant figures. So if the single precision floating point number is use tol = 10E-6
should be about right. However this does not work well for the general case where a_float
might be very small or might be very large.
如何为所有一般情况正确计算 tol
?我特别对 C 或 C++ 案例感兴趣.
How does one calculate tol
correctly for all general cases? I am interested in C or C++ cases specifically.
推荐答案
这篇博文包含一个例子,相当简单的实现,以及背后的详细理论http://randomascii.wordpress.com/2012/02/25/比较浮点数-2012 版/它也是系列之一,因此您可以随时阅读更多内容.简而言之:对大多数数字使用 ULP,对接近零的数字使用 epsilon,但仍有一些注意事项.如果您想确定您的浮点数学,我建议您阅读整个系列.
This blogpost contains an example, fairly foolproof implementation, and detailed theory behind it http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ it is also one of a series, so you can always read more. In short: use ULP for most numbers, use epsilon for numbers near zero, but there are still caveats. If you want to be sure about your floating point math i recommend reading whole series.
这篇关于浮点相等和公差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!