I'm looking to randomize a BigInteger. The intent is to pick a number from 1 to 8180385048. Though, from what I noticed, the BigInteger(BitLen, Random) does it from n to X2-1, I'd want some unpredictable number. I tried to make a method that would do it, but I keep running into bugs and have finally given in to asking on here. :P Does anyone have any suggestions on how to do this?
从文档来看Random.nextInt(int n) http://download-llnw.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt%28int%29显然需要解决同样的问题,他们似乎得出的结论是,你不能比“超出范围时重新采样”做得更好,但惩罚预计可以忽略不计。
来自文档:
The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 231 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=230+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop terminates is 2.
我建议你简单地使用随机化构造函数 http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html#BigInteger%28int,%20java.util.Random%29您提到并迭代,直到达到范围内的值,例如如下所示:
public static BigInteger rndBigInt(BigInteger max) {
Random rnd = new Random();
do {
BigInteger i = new BigInteger(max.bitLength(), rnd);
if (i.compareTo(max) <= 0)
return i;
} while (true);
}
public static void main(String... args) {
System.out.println(rndBigInt(new BigInteger("8180385048")));
}
对于您的特定情况(最大值 = 8180385048),必须重申的概率(即使一次)约为 4.8%,所以不用担心:-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)