获取一个集中在中心的随机数

2022-01-17 00:00:00 algorithm random numbers javascript

是否可以得到1-100之间的随机数,并将结果主要保持在40-60范围内?我的意思是,它很少会超出这个范围,但我希望它主要在那个范围内...... JavaScript/jQuery 有可能吗?

Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be mainly within that range... Is it possible with JavaScript/jQuery?

现在我只使用基本的 Math.random() * 100 + 1.

Right now I'm just using the basic Math.random() * 100 + 1.

推荐答案

最简单的方法是生成两个 0-50 的随机数并将它们相加.

The simplest way would be to generate two random numbers from 0-50 and add them together.

这给出了一个偏向 50 的分布,以同样的方式将两个骰子偏向 7.

This gives a distribution biased towards 50, in the same way rolling two dice biases towards 7.

事实上,通过使用更多的骰子",(正如@Falco 建议的那样),您可以更接近钟形曲线:

In fact, by using a larger number of "dice" (as @Falco suggests), you can make a closer approximation to a bell-curve:

function weightedRandom(max, numDice) {
    let num = 0;
    for (let i = 0; i < numDice; i++) {
        num += Math.random() * (max/numDice);
    }    
    return num;
}

JSFiddle:http://jsfiddle.net/797qhcza/1/

相关文章