duanou3868 2018-06-19 17:05
浏览 33

使用modulo获取范围内的随机整数

My goal is to have a seeded PRNG that generates the same numbers both in Javascript and in PHP. I found a linear congruential generator that works in both environments, but my problem is that if I use a division to get it in the range I need, Javascript and PHP's different floating precision means the numbers will be slightly different.

I'm not really sure if it would be a problem in my specific case (I don't need numbers higher than 100), but to get around it I tried using the modulo operator. As I expected, since the numbers that the PRNG generates are relatively small, the probability of each number coming out gets smaller as the numbers get higher.

Are there any (possibly simple) algorithms that would work reliably both client and server side?

This is the generator in Javascript that uses the modulo operator to get the integers in range, along with some code that demonstrates that higher numbers come out less frequently

function SeededRandom(newSeed) {
    this.seed = newSeed;
    this.Random = function (max) {//max value not included
        this.seed = (this.seed * 20077 + 12345) % 32768;
        return this.seed % max;
    }
}

const MAX_ITER = 1000000;
const MAX_VALUE = 10000;

let random = new SeededRandom(123456);
let array = new Array(MAX_VALUE).fill(0);

for (let iii = 0; iii < MAX_ITER; iii++) {
    array[random.Random(MAX_VALUE)]++;
}

for (let iii = 0; iii < MAX_VALUE; iii++) {
    console.log(iii + ". " + (array[iii] / MAX_ITER));
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
    • ¥15 蓝桥oj3931,请问我错在哪里
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state