Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中返回负值的LCG_Java_Javascript_Random - Fatal编程技术网

在Java中返回负值的LCG

在Java中返回负值的LCG,java,javascript,random,Java,Javascript,Random,我已经将kotarou3的JavaScript中的LCG算法移植到Java中。原始代码声明,如果没有向函数传递任何参数,它应该返回[0,1]中的实数,就像Math.random一样。但是,我的实现偶尔会返回-1到0之间的负数 代码: private int[] startingSeed = new int[]{(int) Math.floor(Math.random() * 0x10000), (int) Math.floor(Math.random() * 0x10000),

我已经将kotarou3的JavaScript中的LCG算法移植到Java中。原始代码声明,如果没有向函数传递任何参数,它应该返回[0,1]中的实数,就像Math.random一样。但是,我的实现偶尔会返回-1到0之间的负数

代码:

private int[] startingSeed = new int[]{(int) Math.floor(Math.random() * 0x10000),
        (int) Math.floor(Math.random() * 0x10000),
        (int) Math.floor(Math.random() * 0x10000),
        (int) Math.floor(Math.random() * 0x10000)};

private int[] seed = new int[4];

public double random() {
    this.seed = this.nextFrame();
    double result = (this.seed[0] << 16 >>> 0) + this.seed[1];
    result = result / 0x100000000L;
    return result;
}

public int[] nextFrame() {
    int[] seed = this.seed;
    int n = 1;

    for(int frame = 0; frame < n; ++frame) {

        int[] a = new int[]{0x5D58, 0x8B65, 0x6C07, 0x8965};
        int[] c = new int[]{0, 0, 0x26, 0x9EC3};

        int[] nextSeed = new int[]{0, 0, 0, 0};
        int carry = 0;

        for (int cN = seed.length - 1; cN >= 0; --cN) {
            nextSeed[cN] = carry;
            carry = 0;

            int aN = seed.length - 1;
            int seedN = cN;
            for(; seedN < seed.length; --aN, ++seedN) {
                int nextWord = a[aN] * seed[seedN];
                carry += nextWord >>> 16;
                nextSeed[cN] += nextWord & 0xFFFF;
            }
            nextSeed[cN] += c[cN];
            carry += nextSeed[cN] >>> 16;
            nextSeed[cN] &= 0xFFFF;
        }

        seed = nextSeed;
    }
    return seed;
}

原始代码几乎相同,只有数据类型int和double是vars,但算法保持不变。

是否有指向原始算法或JavaScript代码的链接?这样,就可以了解代码行为不同的原因;但如果没有它,可能无法弄清楚这一点。此外,您希望得到什么>>>0要做什么?我觉得在Java中可以做得更简单:LCG只是一个*B+C mod D,Java支持64位整数,这与JavaScript不同,因此nextFrame方法中的所有工作都可以大大简化。我已经了解到,使用>>>0可以确保得到一个介于0和0xFFFFFF之间的整数。@Ikuzen JavaScript=/=Java,在Java中确实如此没什么。另外一个产生负值的种子是[52264、65161、13989、26305],谢谢大家的帮助。我会按照Peter O.的建议,完全重写代码,而不仅仅是将其移植到Java。