我如何使用Math.random()来实现罕见的常见结果

时间:2014-09-23 00:16:55

标签: jquery random

我正在研究一个系统,在这个系统中,随机时间后更换图像。但是我目前在数字1-5之间选择用于显示目的。我想知道我是否可以使用Math.random()来制作一些比其他数字更少的数字。例如,如果我想要数字1一般出现,但想要数字5真的很少,我可以用Math.random()吗?如果不能做到这一点?

我目前的代码:

$(function() {
$("#test").click(function() {
    randomGen();
});

function randomGen() {
var rand = Math.floor((Math.random() * 5) + 1);
var test = Math.floor((Math.random() * 15000) + 1);
    if (rand === 1) { 
        console.log(rand);
    }
    if (rand === 2) {
        console.log(rand);
    }
    if (rand === 3) {
        console.log(rand);
    }
    if (rand === 4) {
        console.log(rand);
    }
    if (rand === 5) {
        console.log(rand);
    }
setTimeout(randomGen, test);
}
});

2 个答案:

答案 0 :(得分:2)

尝试:

var rand = Math.floor(Math.pow(Math.random(), 2) * 5 + 1);

通过将0到1之间的随机数平方,分布向较低的数字倾斜。这比1更常见1,这比3更常见,等等。如果你想调整分布或改变周围的东西,调整指数。

答案 1 :(得分:1)

不,Math.Random不适合直接用于使某些数字看起来比其他数字更频繁。

但是,您可以添加自己的"加权"功能,像这样:

//Returns a random with a 20% chance of 1, 40% chance of 2 or 3
function WeightedRandom()
{
    var num = Math.random() * 100;

    if(num < 20)
        return 1;
    if(num < 60)
        return 2;
    else return 3;
}

这当然是高度手动的,我确信您可以想出一种聪明的方法来使其更加自动化。