如何在Java中创建随机BigDecimal? [英] How can I create a random BigDecimal in Java?
问题描述
这个问题:如何生成随机BigInteger 描述了一种实现与BigIntegers的Random.nextInt(int n)相同语义的方法。
This question: How to generate a random BigInteger describes a way to achieve the same semantics as Random.nextInt(int n) for BigIntegers.
我想对BigDecimal和Random.nextDouble做同样的事情( )。
I would like to do the same for BigDecimal and Random.nextDouble().
上述问题的一个答案建议创建一个随机的BigInteger,然后用随机比例从中创建一个BigDouble。一个非常快速的实验表明这是一个非常糟糕的主意:)
One answer in the above question suggests creating a random BigInteger and then creating a BigDouble from it with a random scale. A very quick experiment shows this to be a very bad idea :)
我的直觉是使用这种方法需要通过像 n-log10(R)
,其中n是输出中所需精度的位数,R是随机BigInteger。这应该允许存在正确的位数,以便(例如)1 - > 10 ^ -64和10 ^ 64 - > 1.
My intuition is that using this method would require the integer to be scaled by something like n-log10(R)
, where n is the number of digits of precision required in the output and R is the random BigInteger. This should allow the correct number of digits to be present so that (for example) 1 -> 10^-64 and 10^64 -> 1.
缩放值还需要正确选择结果,使其落在[0,1]范围内。
The scaling value also needs to be chosen correctly for the result to fall in the range [0,1].
之前是否有人这样做过,并且他们知道是否结果是否正确分布?有没有更好的方法来实现这一目标?
Has anyone done this before, and do they know if the results are correctly distributed? Is there a better way to achieve this?
编辑:感谢@biziclop纠正我对scale参数的理解。以上不是必需的,恒定的比例因子具有预期的效果。
Thanks to @biziclop for correcting my understanding of the scale argument. The above isn't necessary, a constant scale factor has the desired effect.
供以后参考,我的(显然工作代码)是:
For later reference, my (apparently working code) is:
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;
}
推荐答案
这肯定很容易..如果我只知道你想要什么。对于范围[0,1]中的均匀分布数和精度N十进制数,生成小于10 * N的统一BigInteger,并将其缩小10 * N.
It's surely very easy... if I only knew what you want. For a uniformly distributed number in range [0, 1) and precision N decimal digits generate a uniform BigInteger less than 10*N and scale it down by 10*N.
这篇关于如何在Java中创建随机BigDecimal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!