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

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

问题描述

<块引用>

可能的重复:
浮点/舍入误差的简单示例是什么?

当我执行以下 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屋!

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