【问题标题】:How can I use Math.random() to make rare to common outcomes我如何使用 Math.random() 来产生罕见的常见结果
【发布时间】:2014-11-17 01:30:42
【问题描述】:

我正在开发一个在随机时间后替换图像的系统。但是,我目前让它在数字 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);
}
});

【问题讨论】:

    标签: jquery random


    【解决方案1】:

    试试:

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

    通过在 0 和 1 之间对随机数进行平方,分布会偏向较小的数字。这使得 1 比 2 更常见,后者比 3 更常见,等等。如果您想调整分布或改变周围的事物,请调整指数。

    【讨论】:

    • 这是不对的。这只是对数字应用一个函数以使它们符合指数曲线,而不是使它们显式加权。
    • @Pheonixblade9:这可能就是 OP 的意思。它比真正的加权函数要简单得多,因为它以数学方式调整分布。
    【解决方案2】:

    不,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;
    }
    

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

    【讨论】:

    • 它告诉我“Uncaught ReferenceError: r is not defined”,我不知道你是忘记定义它还是我应该定义它或什么XD
    • 对不起,我很笨,先用C#写的。 :)
    • 太棒了!现在我有另一个问题,它在 2 或 3 次后停止并且即使我有 setTimeout(WeightedRandom, test); 它也不会重复;其中 test 被定义并被赋予一个随机数。不知道为什么会这样。
    • 我不确定为什么会这样,但如果它解决了您的问题,请确保将其标记为正确 - 并随时针对您的新问题提出另一个问题 :)
    • 哈哈是的,我得等 90 分钟再问一个 :P 再次谢谢你!
    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2017-05-08
    相关资源
    最近更新 更多