如何让BigDecimal除法更精确

How to make BigDecimal division more precise

我遇到了 BigDecimals 的问题,简化的想法是:

这是失败的测试:


    @Test
    fun sanityCheckExampleForWhosebug() {
        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"))
    }

缺少什么?

鉴于您的权重总和为 100.000000000000002,sumOfParts 的值为 2000000000.000000040,与您的原始值相差 0.00000004,比 0.00000001.