在Lua中比较数字

我正在检查线段相交,并需要确定交点(xy)是否在线段l2(由点p1p2组成)的边界框内。

以下打印输出展示了我的问题:

交点是(100,300)

print("x",x,">=",math.min(l2.p1.x,l2.p2.x),x >= math.min(l2.p1.x,l2.p2.x))
print("x",x,"<=",math.max(l2.p1.x,l2.p2.x),x <= math.max(l2.p1.x,l2.p2.x))
print("y",y,">=",math.min(l2.p1.y,l2.p2.y),y >= math.min(l2.p1.y,l2.p2.y))
print("y",y,"<=",math.max(l2.p1.y,l2.p2.y),y <= math.max(l2.p1.y,l2.p2.y))

结果如下:

x   100 >=  100 true
x   100 <=  100 false
y   300 >=  140 true
y   300 <=  300 false

发生了什么,如何解决?

(Lua版本5.2.3)

点赞
用户2779972
用户2779972

欢迎使用浮点算术:http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

例如:

> string.format("%.32f", 1/3)
0.33333333333333331482961625624739
> 1/3 == 0.3333333
false

这取决于X和lp*的计算方式。比较浮点数时应使用公差。

> math.abs(1/3 - 0.33) == 0
false
> math.abs(1/3 - 0.33333) < 1/10^6
false
> math.abs(1/3 - 0.33333) < 1/10^5
true
2015-09-25 09:11:56