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

问题描述 投票:0回答:1

我有一个问题,我需要一定比例的通话记录,系统不允许只设置该百分比。因此,在我的代码中,我需要对其进行计算,然后说20%不要记录。

有人建议使用Math.Random()函数来做到这一点,它应该保持平衡,但我看不到如何生成随机数。

so:

var desiredrecordpercentage = 80

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

    disable recording;

}

我只是看不到每100个电话将如何平衡该数字,它能否在100个电话中两次生成相同的电话号码?还是工作到100,然后重新开始?

javascript math ecmascript-6 percentage
1个回答
0
投票

[每当我需要基于固定概率发生某些事情时,我通常会处理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();

}
© www.soinside.com 2019 - 2024. All rights reserved.