groovy - 为什么 Groovy 以这种方式执行浮点运算?

标签 groovy floating-point

在 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/

相关文章:

用于 CustomClass 和数字/字符串的 Groovy CompareTo

javascript - JavaScript 中 float 的加法

mysql - 在 Bash 脚本中使用浮点

java - 为什么两个名义上具有相同值的浮点结果不同?

android - 辅助模块中的 Gradle buildSrc 依赖项

gradle - groovy/gradle插件无法有条件地构建

eclipse - 更新 Eclipse : Searching Alternate solutions 时出错

java - Groovy ASTBuilder 多线程性能不佳

c# - C# 中的指数

c++ - std::decimal::decimal64 正确用法,g++ 4.6.3