gpt4 book ai didi

Lua 无法评估 math.abs(29.7 - 30) <= 0.3

转载 作者:行者123 更新时间:2023-12-04 22:21:53 27 4
gpt4 key购买 nike

今天早上我在我的 Lua 脚本上发现了一个错误,看起来很奇怪。这种评估怎么会以这种方式失败?示例可在 here 中进行测试

第一个例子:

if( math.abs(29.7 - 30) <=  0.3 ) then
result = 1
else
result = 0
end
print("result = "..result )
-->> result = 0

第二个例子:

if( 0.3 <=  0.3 ) then
result = 1
else
result = 0
end
print("result = "..result )
-->> result = 1

第三个例子

if( math.abs(29.7-30) == 0.3 )then
print("Lua says: "..math.abs(29.7-30).." == 0.3")
else
print("Lua says: "..math.abs(29.7-30).." ~= 0.3")
end
-->> Lua says: 0.3 ~= 0.3 WHAT?

我真的很困惑,我想了解这一点以避免将来出现类似的错误。谢谢

最佳答案

Lua 使用 (IEEE 754) 64 位 double float 这一事实打击了您。

看下面的例子
> print(0.3 == 0.3)
true
> print(0.3 <= 0.3)
true
> print(0.3 >= 0.3)
true

0.3 的实际值内存中是:
> print(string.format("%1.64f",math.abs(-0.3)))
0.2999999999999999888977697537484345957636833190917968750000000000

现在看你的例子:
> print(math.abs(29.7-30) == 0.3)
false
> print(math.abs(29.7-30) >= 0.3)
true
> print(math.abs(29.7-30) <= 0.3)
false

29.7-30 的实际值是:
> print(string.format("%1.64f",29.7-30))
-0.3000000000000007105427357601001858711242675781250000000000000000

math.abs(29.7-30) 的实际值是:
> print(string.format("%1.64f", math.abs(29.7-30))
0.3000000000000007105427357601001858711242675781250000000000000000

math.abs(-0.3) 的值只是为了好玩是:
> print(string.format("%1.64f", math.abs(-0.3)))
0.2999999999999999888977697537484345957636833190917968750000000000

你的问题有两种解决方法,第一种是阅读What Every Computer Scientist Should Know About Floating-Point Arithmetic ,并理解它:-)。第二种解决方案是将 Lua 配置为使用另一种数字类型,请参阅 Values and Types提示。

编辑我只是想到了另一种“解决”问题的方法,但这有点像黑客,并且不能保证总是有效。您可以通过首先将 float 转换为具有固定精度的字符串来在 lua 中使用定点数。

在你的情况下,它看起来像:

a = string.format("%1.1f", math.abs(29.7 - 30))
print(a == "0.3")

或者更强大一点:

a = string.format("%1.1f", math.abs(29.7 - 30))
print(a == string.format("%1.1f", 0.3))

但是,对于所有比较,您必须确保使用足够且相同的精度。

关于Lua 无法评估 math.abs(29.7 - 30) <= 0.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16332553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com