所以,我的想法是将$2.00分给10个人,每个人随机收到$x.xx的金额。(N和M始终限制为2个小数点且>0)
例如:{0.12, 0.24, 1.03, 0.01, 0.2, 0.04, 0.11, 0.18, 0.05, 0.02}
目前我尝试过:
例如:{0.12, 0.24, 1.03, 0.01, 0.2, 0.04, 0.11, 0.18, 0.05, 0.02}
目前我尝试过:
private static BigDecimal[] randSum(int n, double m)
{
Random rand = new Random();
BigDecimal randNums[] = new BigDecimal[n], sum = new BigDecimal(0).setScale(2);
for (int i = 0; i < randNums.length; i++)
{
randNums[i] = new BigDecimal(rand.nextDouble()).setScale(2, RoundingMode.HALF_EVEN);
sum = sum.add(randNums[i]);
}
for (int i = 0; i < randNums.length; i++)
{
BigDecimal temp1 = randNums[i].divide(sum, 2, RoundingMode.HALF_EVEN);
BigDecimal temp2 = temp1.multiply(new BigDecimal(m).setScale(2));
randNums[i] = temp2;
}
return randNums;
}
public static void main(String[] args)
{
BigDecimal d[] = randSum(5, 2);
double sum = 0;
for (BigDecimal n : d)
{
sum += n.doubleValue();
System.out.println(n);
}
System.out.println("total: " + sum);
}
但是BigDecimal太复杂了,而且它们的总和有时是1.98或2.01。双精度浮点数不适用于Double-precision floating-point。
代码来自:
m == 1.234
怎么办?你永远无法生成这样的数值。 - Tagir Valeev