为什么Lua算术不等于自己? [英] Why is Lua arithmetic is not equal to itself?

查看:244
本文介绍了为什么Lua算术不等于自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


当我执行下面的Lua代码时:

  a = 5.6 
b = 14 * 0.4
c = 11.2 / 2
d = 28 * 0.2
print(a == b)
print(a == c)
print(a == d)
print(b == c)
print(b == d)
print(c == d)
pre>

我得到以下结果:

$ p $ false
true
false
false
true
false

有人可以解释为什么14 * 0.4和28 * 0.2不等于5.6?

谢谢

你正在处理二进制浮点数的自然不精确性。您的电话号码 a 可能是5.5999999999999996,而您的结果 b 可能是5.6000000000000005,不等于

b
$ b实际上,这里的计算和Python所做的一样:

 >> ;> 5.6 
5.5999999999999996
>>> 14 * 0.4
5.6000000000000005

这种行为对于二进制浮点数的所有实现都是通用的。

Possible Duplicate:
What is a simple example of floating point/rounding error?

When I execute the following Lua code:

a = 5.6
b = 14 * 0.4
c = 11.2 / 2
d = 28 * 0.2
print( a == b )
print( a == c )
print( a == d )
print( b == c )
print( b == d )
print( c == d )

I get the following results:

false
true
false
false
true
false

Can someone explain why 14 * 0.4 and 28 * 0.2 are not equal to 5.6?

Thanks

解决方案

You are dealing with the natural imprecision of binary floating point numbers. Your number a might be 5.5999999999999996 and your result b might be 5.6000000000000005, which are not equal.

In fact, here is the same calculation as done by Python:

>>> 5.6
5.5999999999999996
>>> 14 * 0.4
5.6000000000000005

This behaviour is common to all implementations of binary floating point numbers.

这篇关于为什么Lua算术不等于自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆