范围内的随机自然数函数Typescript返回我不是那么随机的数字



我目前正在研究一个应该在特定范围内生成数字的函数。示例:如果范围的最小值是1,最大值是5,那么它应该返回一个介于1和5之间或等于1和5的数字。

这是我到目前为止的代码:

function getRandomNumber(min: number, max: number): number {
    max = max + 1; // in order to include the max value
    return Math.floor(Math.random() * (max - min) + min);
}

此函数确实按预期工作,但不幸的是,一些数字经常按顺序生成。示例:我定义了1到5的范围,函数的输出将类似于:1,1,1,1,1,5,5,5,1,1,1,1,5,1,1,1,5,1,1,4,4,2,2,3,1,1,1,1,5,1,5,1,5,5,1,1,1,1,3

正如我们所看到的,范围内的所有数字都被包括在内,但由于某种原因,某些数字(例如1和5)在这种情况下通常是按顺序生成的,并且通常比它们应该被归类为"随机"(imo)的频率要高。

我的问题是,如果我在我的代码做错了什么,或者如果这应该是正常的行为。

看起来是平均分布的…

function getRandomNumber(min, max) {
    max = max + 1;
    return Math.floor(Math.random() * (max - min) + min);
}
const count = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
for (let i = 0; i < 1e6; i++) count[getRandomNumber(1, 5)]++;
console.log(count);

最新更新