[英]How to make BigDecimal division more precise
I'm having an issue with BigDecimal
s, the simplified idea is to:我遇到了
BigDecimal
的问题,简化的想法是:
total
total
定义一个值total
in 3 parts
defined by weights
, these weights are 3 double values that add up to 100.0
total
分成由weights
定义的 3 个parts
,这些权重是 3 个加起来为100.0
的双精度值parts
parts
total
, the error should be at most 0.00000001total
,误差最多应该是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.