在 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
是什么导致了这种行为?
最佳答案
你的def
:有BigDecimals
groovy:000> p1 = 0.1
===> 0.1
groovy:000> p1.getClass()
===> class java.math.BigDecimal
并且 equals
无法比较 BigDecimal 和 native 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
中。由于两边都是 Number:s。
关于groovy - 为什么 Groovy 以这种方式执行浮点运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27828103/