Why does Groovy perform floating point arithmetic in this way?

Awakening floating point arithmetic in Groovy. Don't know why / how / what groovy is doing backstage to trigger these different types of behavior?

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 

I thought this was due to BigDecimal, but then I tried this.

 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 

What causes this behavior?

+5
source share
1 answer

your def : s is BigDecimals

 groovy:000> p1 = 0.1 ===> 0.1 groovy:000> p1.getClass() ===> class java.math.BigDecimal 

And equals not suitable for comparing between BigDecimal and 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 

Not sure why == works for [Dd] ouble.

 groovy:000> p1.equals(0.1d) ===> false groovy:000> p1==0.1d ===> true 

My guess would be that it stalled in DefaultTypeTransformation.compareToWithEqualityCheck . Since both sides: Number: s.

+5
source

Source: https://habr.com/ru/post/1210601/


All Articles