有没有一种简单的方法来检查2个浮点数是否大致相等?

时间:2018-06-30 02:48:37

标签: lua floating-point

在LUA中,有没有一种方法可以检查浮点数是否大致相等?

2 个答案:

答案 0 :(得分:1)

只需设置一个阈值。如果两个值之间的差小于阈值,则认为它们相等:

a = 1.23456789
b = 1.23456777

threshold = 0.000001

diff = math.abs(a - b) -- Absolute value of difference
print(diff < threshold) -- True if difference is less than threshold

输出:

true

答案 1 :(得分:1)

您还比较了它们的十进制表示形式:

function decimal(x)
  return string.format("%.3f",x)
end

print(decimal(x)==decimal(y))
相关问题