为什么这些浮点数不被评估为相等?
在下面的代码中,如果 x0 == x1 且 y0 == y1,那么它应该告诉我这一点。在我使用的示例中,它们是。然而,Python 只表示 x 值相等,而不表示 y 值相等。
这是代码:
print "arc2x0 = ", arc2x0, ", arc2x1 = ", arc2x1
print "arc2y0 = ", arc2y0, ", arc2y1 = ", arc2y1
if arc2x0 == arc2x1:
print "x0 == x1"
else:
print "x0 != x1"
if arc2y0 == arc2y1:
print "y0 == y1"
else:
print "y0 != y1"
这是输出:
arc2x0 = 5 , arc2x1 = 5.0
arc2y0 = -4.16026900507 , arc2y1 = -4.16026900507
x0 == x1
y0 != y1
知道为什么 y 值测试相等吗?这些值的计算方式相同。也许还有比我所看到的更精确的不相等的精度?有什么方法可以打印该精度或任何其他关于如何调试它的想法?
In the following code, if x0 == x1 and y0 == y1, then it should tell me so. In the example I'm using, they are. However, Python is only saying the x values are equal, not the y.
Here's the code:
print "arc2x0 = ", arc2x0, ", arc2x1 = ", arc2x1
print "arc2y0 = ", arc2y0, ", arc2y1 = ", arc2y1
if arc2x0 == arc2x1:
print "x0 == x1"
else:
print "x0 != x1"
if arc2y0 == arc2y1:
print "y0 == y1"
else:
print "y0 != y1"
And here's the output:
arc2x0 = 5 , arc2x1 = 5.0
arc2y0 = -4.16026900507 , arc2y1 = -4.16026900507
x0 == x1
y0 != y1
Any idea why the y values are testing as equal? These values are calculated in the same way. Maybe there's more precision beyond what I'm seeing that isn't equal? Any way to print that precision or any other ideas on how to debug this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,比您所看到的更精确。问题是 == 运算符通常不应该与浮点数一起使用。浮点数的精度有限,会累积舍入误差,并且由于无法精确存储所有十进制值而导致不精确。例如,
比较浮点数是否相等的最佳方法是比较它们是否几乎相等:
通过比较浮点数之间的差异是否小于 epsilon 值,该值指示多接近才被认为足够接近相等。
您始终可以使用decimal.Decimal类型来避免这些问题。
Yes there is more precision beyond what you're seeing. The problem is that the == operator should not usually be used with floats. Floating point numbers have limited precision and accumulate rounding error, and imprecision from not being able to store all decimal values precisely. e.g.
The best way to compare floats for equality is to compare if they are nearly equal:
By comparing if the difference between floats is less than an epsilon value, which indicates how close is considered close enough to be equal.
You can always use the decimal.Decimal type to avoid these problems.
这是由于浮点的工作原理所致,您应该手动截断数字以将精度强制达到您想要的数字:
但我认为最好的方法是使用十进制:
This is due to how floating point works,you should manually truncate the numbers to force the precision to the figures you want:
But i think the best way would be to use decimal: