我正在尝试计算以下内容:
(1 - (1/365)) * (1 - (2/365) = 0.99727528617
Run Code Online (Sandbox Code Playgroud)
我想存储整个小数.这是我的代码,但它给了我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());
Run Code Online (Sandbox Code Playgroud)
输出:
P(3) = 1
Run Code Online (Sandbox Code Playgroud)
那是因为你正在计算的除法是用0表示的.引用方法divide(divisor, roundingMode)Javadoc:
返回
BigDecimal其值为(this / divisor),且其比例为的值this.scale().
在这种情况下,this.scale()是指分子,其为0,因为分子是规模BigDecimal.valueOf(n),与n为整数.
您需要更改此分区才能使用,divide(divisor, scale, roundingMode)并指定所需的比例.
| 归档时间: |
|
| 查看次数: |
1069 次 |
| 最近记录: |