为什么 Lua 算术不等于自身? [英] Why is Lua arithmetic is not equal to itself?
问题描述
可能的重复:
浮点/舍入误差的简单示例是什么?
当我执行以下 Lua 代码时:
a = 5.6b = 14 * 0.4c = 11.2/2d = 28 * 0.2打印( a == b )打印( a == c )打印( a == d )打印( b == c )打印( b == d )打印( c == d )
我得到以下结果:
false真的错误的错误的真的错误的
谁能解释为什么 14 * 0.4 和 28 * 0.2 不等于 5.6?
谢谢
您正在处理二进制浮点数的自然不精确性.您的数字 a
可能是 5.5999999999999996 而您的结果 b
可能是 5.6000000000000005,它们不相等.
其实这里和Python做的计算是一样的:
<预><代码>>>>5.65.5999999999999996>>>14*0.45.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屋!