如何在Java中创建随机BigDecimal?

Mik*_*ton 5 java random math biginteger bigdecimal

这个问题:如何生成随机BigInteger描述了一种实现与BigIntegers的Random.nextInt(int n)相同语义的方法.

我想对BigDecimal和Random.nextDouble()做同样的事情.

上述问题中的一个答案建议创建一个随机的BigInteger,然后用随机比例从中创建一个BigDouble.一个非常快速的实验表明这是一个非常糟糕的主意:)

我的直觉是使用这种方法需要通过类似的方式缩放整数n-log10(R),其中n是输出中所需的精度位数,R是随机BigInteger.这应该允许存在正确的位数,以便(例如)1 - > 10 ^ -64和10 ^ 64 - > 1.

还需要正确选择缩放值,使结果落在[0,1]范围内.

有没有人以前做过这个,他们知道结果是否正确分布?有没有更好的方法来实现这一目标?

编辑:感谢@biziclop纠正我对scale参数的理解.以上不是必需的,恒定的比例因子具有期望的效果.

为了以后的参考,我(显然是工作代码)是:

private static BigDecimal newRandomBigDecimal(Random r, int precision) {
    BigInteger n = BigInteger.TEN.pow(precision);
    return new BigDecimal(newRandomBigInteger(n, r), precision);
}

private static BigInteger newRandomBigInteger(BigInteger n, Random rnd) {
    BigInteger r;
    do {
        r = new BigInteger(n.bitLength(), rnd);
    } while (r.compareTo(n) >= 0);

    return r;
}
Run Code Online (Sandbox Code Playgroud)

maa*_*nus 2

这肯定很容易...只要我知道你想要什么就好了。对于范围 [0, 1) 和精度 N 个十进制数字的均匀分布数字,生成小于 10* N 的统一 BigInteger,并将其缩小 10 *N。