当使用java.util.Random类时,如何获取从调用nextInt()方法获得的值N次,但是以更有效的方式(具体在O(1)中)?
例如,如果我构造一个具有特定种子值的Random对象,并且我想得到第100,000个“nextInt()值”(即,在调用方法nextInt()100,000次之后获得的值)一个快速的方式,我能做到吗?
为简单起见,假设JDK的版本为1.7.06,因为可能需要知道Random类中某些私有字段的确切值。说到这里,我发现以下字段与随机值的计算有关:
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
在探索了一些关于随机性之后,我发现使用线性同余生成器获得随机值。执行算法的实际方法是方法next(int):
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
算法的相关行是获取下一个种子值的行:
nextseed = (oldseed * multiplier + addend) & mask;
因此,更具体地说,是否有一种方法可以推广这个公式来获得“第n个nextseed”值?我假设在那之后,我可以通过让变量“bits”为32来获取第n个int值(方法nextInt()只调用next(32)并返回结果)。
提前致谢
PS:也许这个问题更适合mathexchange?
答案 0 :(得分:5)
你可以在O(log N)
时间内完成。从s(0)
开始,如果我们暂时忽略模数(2 48 ),我们可以看到(使用m
和a
作为{{1}的简写<}和multiplier
)
addend
现在,s(1) = s(0) * m + a
s(2) = s(1) * m + a = s(0) * m² + (m + 1) * a
s(3) = s(2) * m + a = s(0) * m³ + (m² + m + 1) * a
...
s(N) = s(0) * m^N + (m^(N-1) + ... + m + 1) * a
可以通过重复平方的模幂运算在m^N (mod 2^48)
步骤中轻松计算。
另一部分有点复杂。暂时忽略模数,几何和是
O(log N)
使计算模(m^N - 1) / (m - 1)
有点不重要的原因是2^48
与模数无关。但是,因为
m - 1
m = 0x5DEECE66DL
的最大公约数,模数为4,而m-1
具有模(m-1)/4
模inv
模{}。让
2^48
然后
c = (m^N - 1) (mod 4*2^48)
所以
(c / 4) * inv ≡ (m^N - 1) / (m - 1) (mod 2^48)
M ≡ m^N (mod 2^50)
获取
inv
答案 1 :(得分:2)
我接受了Daniel Fischer的答案,因为它是正确的并给出了一般解决方案。使用Daniel的答案,这是一个具有java代码的具体示例,它显示了公式的基本实现(我广泛使用了BigInteger类,因此它可能不是最优的,但我确认了实际调用nextInt方法的基本方法的显着加速( )N次):
import java.math.BigInteger;
import java.util.Random;
public class RandomNthNextInt {
// copied from java.util.Random =========================
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
private static long initialScramble(long seed) {
return (seed ^ multiplier) & mask;
}
private static int getNextInt(long nextSeed) {
return (int)(nextSeed >>> (48 - 32));
}
// ======================================================
private static final BigInteger mod = BigInteger.valueOf(mask + 1L);
private static final BigInteger inv = BigInteger.valueOf((multiplier - 1L) / 4L).modInverse(mod);
/**
* Returns the value obtained after calling the method {@link Random#nextInt()} {@code n} times from a
* {@link Random} object initialized with the {@code seed} value.
* <p>
* This method does not actually create any {@code Random} instance, instead it applies a direct formula which
* calculates the expected value in a more efficient way (close to O(log N)).
*
* @param seed
* The initial seed value of the supposed {@code Random} object
* @param n
* The index (starting at 1) of the "nextInt() value"
* @return the nth "nextInt() value" of a {@code Random} object initialized with the given seed value
* @throws IllegalArgumentException
* If {@code n} is not positive
*/
public static long getNthNextInt(long seed, long n) {
if (n < 1L) {
throw new IllegalArgumentException("n must be positive");
}
final BigInteger seedZero = BigInteger.valueOf(initialScramble(seed));
final BigInteger nthSeed = calculateNthSeed(seedZero, n);
return getNextInt(nthSeed.longValue());
}
private static BigInteger calculateNthSeed(BigInteger seed0, long n) {
final BigInteger largeM = calculateLargeM(n);
final BigInteger largeMmin1div4 = largeM.subtract(BigInteger.ONE).divide(BigInteger.valueOf(4L));
return seed0.multiply(largeM).add(largeMmin1div4.multiply(inv).multiply(BigInteger.valueOf(addend))).mod(mod);
}
private static BigInteger calculateLargeM(long n) {
return BigInteger.valueOf(multiplier).modPow(BigInteger.valueOf(n), BigInteger.valueOf(1L << 50));
}
// =========================== Testing stuff ======================================
public static void main(String[] args) {
final long n = 100000L; // change this to test other values
final long seed = 1L; // change this to test other values
System.out.println(n + "th nextInt (formula) = " + getNthNextInt(seed, n));
System.out.println(n + "th nextInt (slow) = " + getNthNextIntSlow(seed, n));
}
private static int getNthNextIntSlow(long seed, long n) {
if (n < 1L) {
throw new IllegalArgumentException("n must be positive");
}
final Random rand = new Random(seed);
for (long eL = 0; eL < (n - 1); eL++) {
rand.nextInt();
}
return rand.nextInt();
}
}
注意:注意方法initialScramble(long),它用于获取第一个种子值。这是使用特定种子初始化实例时Random类的行为。