Math.random() Javascript - 百分比和权重

Math.random() Javascript - Percentage and weight

我有一个问题,我需要有一定百分比的通话记录,系统不允许只设置它。所以在我的代码中我需要计算它然后说 20% 不记录。

有人建议使用 Math.Random() 函数来执行此操作,它应该会平衡,但我看不出如何生成随机数。

所以:

var desiredrecordpercentage = 80

var percentageCheck = Math.random()*100;
if (percentageCheck >= desiredrecordpercentage){

    disable recording;

}

我只是看不出每 100 次调用该数字如何平衡,它能否在 100 次调用中两次生成相同的数字?还是通过 100 次后重新开始?

每当我需要基于固定概率发生某些事情时,我通常会处理 0 和 1 之间的浮点数,这与 Math.random() 输出随机值的方式相同。

我已经重写了您的程序以适应概率,但如果您愿意,使用百分比也没有错。我只是认为乘以 100 并没有多大用处,它并没有使程序更具可读性(至少对我而言)。

我很久以前看过一个很棒的视频,它描述了这个概念。

Probability Basics - The Nature of Code By Daniel Shiffman (YouTube)

var desiredRecord = 0.8;   // 1: record everything, 
                           // 0: record nothing

var check = Math.random();  // check will be anywhere between 0 and 1

if (check > desiredRecord) { // will be true if check is between 0.81 and 0.99
                             // but false if check is below 0.8 
                             // which is more probable since 80 is the
                             // majority or the percentile

    disable_recording();

}

上面的代码可以工作,大多数时候 disable_recording() 不会被调用,因为 random() 函数很可能会输出小于 0.8 的值。但偶尔(20% 的时间)该函数会被调用。