ksc*_*t90 5 floating-point groovy
在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
Run Code Online (Sandbox Code Playgroud)
我认为它与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
Run Code Online (Sandbox Code Playgroud)
是什么导致了这种行为?
你的def:有的BigDecimals
groovy:000> p1 = 0.1
===> 0.1
groovy:000> p1.getClass()
===> class java.math.BigDecimal
Run Code Online (Sandbox Code Playgroud)
并且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
Run Code Online (Sandbox Code Playgroud)
还不确定,为什么==适用于[Dd] ouble.
groovy:000> p1.equals(0.1d)
===> false
groovy:000> p1==0.1d
===> true
Run Code Online (Sandbox Code Playgroud)
我的猜测是,它被埋没了DefaultTypeTransformation.compareToWithEqualityCheck.由于双方都是数字:s.
| 归档时间: |
|
| 查看次数: |
426 次 |
| 最近记录: |