【问题标题】:Implementation using linear congruential equation in java在java中使用线性同余方程实现
【发布时间】:2014-02-20 11:37:20
【问题描述】:

我在 Random 类下看到了 Java 中的 LCG 实现,如下所示:

/*
 * This is a linear congruential pseudorandom number generator, as
 * defined by D. H. Lehmer and described by Donald E. Knuth in
 * <i>The Art of Computer Programming,</i> Volume 3:
 * <i>Seminumerical Algorithms</i>, section 3.2.1.
 *
 * @param  bits random bits
 * @return the next pseudorandom value from this random number
 *         generator's sequence
 * @since  1.1
 */

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));
}

但下面的链接告诉 LCG 应该是 x2=(ax1+b)modM

https://math.stackexchange.com/questions/89185/what-does-linear-congruential-mean

但上面的代码看起来并不相似。相反,它使用 & 代替以下行的模运算

nextseed = (oldseed * multiplier + addend) & mask;

有人可以帮我理解这种使用 & 代替模运算的方法吗?

【问题讨论】:

    标签: java math random


    【解决方案1】:

    使用2^n - 1 形式的掩码进行位与运算与计算模2^n 的数字相同:数字中的任何高1 都是2^n 的倍数,因此可以安全地丢弃。但是请注意,如果您将模数设为 2 的幂(而不是 2 的幂减一),则某些乘数/加数组合的效果非常差。该代码很好,但请确保它适合您的常量。

    【讨论】:

      【解决方案2】:

      如果mask + 1 是 2 的幂,则可以使用。

      例如,如果你想做模 4,你可以写 x &amp; 3 而不是 x % 4 以获得相同的结果。

      但是请注意,这要求x 是一个正数

      【讨论】:

        猜你喜欢
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        • 2014-04-21
        • 1970-01-01
        • 1970-01-01
        • 2013-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多