简体   繁体   English

Groovy与Java-浮点精度的差异

[英]Groovy vs Java - difference in floating point accuracy

What could be the reason for difference in floating point accuracy here? 这里浮点精度不同的原因可能是什么?

def "emi test"(){
        given:
        def P =  6000000.00
        def n = 20 * 12
        def r = (8.35/12)/100

        double emi_g = (P * r * (1+r).power(n))  / ((1+r).power(n) - 1)
        double emi_j= (P * r * Math.pow(1+r,n)) / (Math.pow(1+r,n)-1);
        expect:
        emi_g == emi_j
    }

result: 结果:

emi_g == emi_j
|     |  |
|     |  51501.177737160346
|     false
51501.177737160666

The difference is explained by the data type of the results. 差异由结果的数据类型解释。

When run in a shell, the types of your results are: 在shell中运行时,结果类型为:

groovy:000> emi_g.getClass()
===> class java.math.BigDecimal
groovy:000> emi_j.getClass()
===> class java.lang.Double

Groovy's implementation returns a BigDecimal , which has better precision than Double Groovy的实现返回一个BigDecimal ,它的精度比Double

The issue is related to types. 问题与类型有关。

(1 + r).power(n) - 1 evaluates to a BigDecimal (1 + r).power(n) - 1计算为BigDecimal

P * r * (1 + r).power(n) evaluates to a BigDecimal P * r * (1 + r).power(n)计算结果为BigDecimal

P * r * Math.pow(1 + r, n) evaluates to a Double P * r * Math.pow(1 + r, n)计算为Double

Math.pow(1 + r, n) - 1 evaluates to a Double Math.pow(1 + r, n) - 1计算为Double

It isn't clear what your requirements are and whether or not you care about the precision being lost and knowing those requirements would help describe how to get the desired behavior. 目前尚不清楚您的要求是什么,以及您是否在乎精度的损失,知道这些要求将有助于描述如何获得所需的行为。 The answer to the question as asked... 按要求回答问题...

What could be the reason for difference in floating point accuracy here? 这里浮点精度不同的原因可能是什么?

Is because the expressions evaluate to different types and the rules associated with dividing a Double by a Double (and the fact that you are the numerator and denominator values are in a Double to begin with, as opposed to BigDecimial ) cause you to lose some precision. 就是因为表达式的计算结果不同类型和与分割相关联的规则DoubleDouble (而事实上,你是在分子和分母的值是一个Double首先,相对于BigDecimial ),因为你失去一些精度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM