在Groovy中尝试浮点运算。不知道为什么/如何/为什么groovy在幕后做这些不同类型的行为?
double point2 = 0.2
double point1 = 0.1
double point3 = 0.3
assert point2 + point1 == point3 // false, as expected
| | | | |
0.2 | 0.1 | 0.3
| false
0.30000000000000004
float point2 = 0.2
float point1 = 0.1
float point3 = 0.3
assert point2 + point1 == point3 // false, as expected
| | | | |
0.2 | 0.1 | 0.3
| false
0.30000000447034836
def point2 = 0.2
def point1 = 0.1
def point3 = 0.3
assert point2 + point1 == point3 // this returns true
assert 0.2 + 0.1 == 0.3 // this returns true
我认为它与BigDecimal有关,但后来我尝试了这个。
BigDecimal point2 = 0.2
BigDecimal point1 = 0.1
BigDecimal point3 = 0.3
float point4 = 0.4
assert point1 + point3 == point4
| | | | |
0.1 | 0.3 | 0.4
0.4 false
导致此行为的原因是什么?
答案 0 :(得分:5)
您的def
:s有BigDecimals
groovy:000> p1 = 0.1
===> 0.1
groovy:000> p1.getClass()
===> class java.math.BigDecimal
并且equals
无法在BigDecimal和本机float / double
groovy:000> p1.equals(0.1f)
===> false
groovy:000> p1.equals(0.1)
===> true
groovy:000> p1==0.1f
===> false
groovy:000> p1==0.1
===> true
尚不确定,为什么==
适用于[Dd] ouble。
groovy:000> p1.equals(0.1d)
===> false
groovy:000> p1==0.1d
===> true
我的猜测是,它被DefaultTypeTransformation.compareToWithEqualityCheck
埋葬了。由于双方都是数字:s。