简体   繁体   English

如何使 BigDecimal 除法更精确

[英]How to make BigDecimal division more precise

I'm having an issue with BigDecimal s, the simplified idea is to:我遇到了BigDecimal的问题,简化的想法是:

  • define a value for the totaltotal定义一个值
  • split the total in 3 parts defined by weights , these weights are 3 double values that add up to 100.0total分成由weights定义的 3 个parts ,这些权重是 3 个加起来为100.0的双精度值
  • sum up the parts总结parts
  • the sum should be close to the total , the error should be at most 0.00000001总和应该接近total ,误差最多应该是0.00000001

Here's the failing test:这是失败的测试:


    @Test
    fun sanityCheckExampleForStackOverflow() {
        val whole = BigDecimal.valueOf(2_000_000_000.00)
        val weights = listOf("25.453778250984232", "35.38647064849812", "39.15975110051765").map { BigDecimal(it) }

        val parts = weights.map { weight ->
            // w / 100 * total
            weight.divide(BigDecimal(100)).times(whole)
        }

        val sumOfParts = parts[0] + parts[1] + parts[2]
        val difference = sumOfParts - whole

        assertTrue(difference <= BigDecimal("0.00000001"))
    }

What's missing?少了什么东西?

Given your weights sum to 100.000000000000002, the value of sumOfParts is 2000000000.000000040 , which is 0.00000004 from your original value, which is four times bigger than the desired difference of 0.00000001 .假设您的权重总和为 100.000000000000002,则sumOfParts的值为2000000000.000000040 ,即原始值的0.00000004 ,是所需差值0.00000001的四倍。

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

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