[英]BigDecimal division is rounding up
我正在嘗試計算以下內容:
(1 - (1/365)) * (1 - (2/365) = 0.99727528617
我想存儲整個十進制。 這是我的代碼,但是給了我1的答案:
public BigDecimal probability(int t){
BigDecimal probT; // holds our probability of a single (1-(t/365))
BigDecimal result; // holds our result
result = BigDecimal.ONE; // initialize result to 1
// for 1 to t-1
for (int n = 1; n < t; n++){
int numerator = n; // numerator the value of n
int denominator = 365; // denominator 365
// numberator / denominator (round down)
probT = BigDecimal.valueOf(numerator).divide(BigDecimal.valueOf(denominator), RoundingMode.DOWN);
// 1-answer
probT = BigDecimal.ONE.subtract(probT);
// multiply the probabilities together
result = result.multiply(probT);
}
return result;
}
BigDecimal ans2 = bc.probability(3);
System.out.println("P(3) = " + ans2.toString());
輸出:
P(3) = 1
這是因為您正在計算的除法是使用0的比例進行的。引用方法divide(divisor, roundingMode)
Javadoc:
返回一個
BigDecimal
其值為(this / divisor)
,其標度為this.scale()
。
在這種情況下, this.scale()
指分子的小數位,由於分子為BigDecimal.valueOf(n)
,因此n
為整數,因此為0。
您需要更改此除法以改為使用divide(divisor, scale, roundingMode)
並指定所需的比例。
當為MathContext對象提供的精度設置為0(例如MathContext.UNLIMITED)時,算術運算是精確的,不采用MathContext對象的算術方法也是如此。 (這是5之前的版本中唯一支持的行為。)
作為計算精確結果的必然結果,不使用精度設置為0的MathContext對象的舍入模式設置,因此不相關。 在除法的情況下,精確的商可能具有無限長的十進制擴展; 例如1除以3。
如果商具有無終止的十進制擴展,並且指定了該操作以返回精確的結果,則拋出ArithmeticException。 否則,將返回除法的精確結果,就像其他操作一樣。
要解決此問題,您需要執行以下操作:
// numberator / denominator (round down)
probT = BigDecimal.valueOf(numerator).divide(BigDecimal.valueOf(denominator), 10,RoundingMode.DOWN);
其中10是精度(小數位精度),而RoundingMode.DOWN是舍入模式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.