Php 事件发生的概率

Php 事件发生的概率,php,random,probability,Php,Random,Probability,我想做的是(但完全弄糊涂了)在PHP中生成一个代码,它根据十进制数(最多10位小数)给出的概率执行代码,其中as 1是执行代码的100%概率。以下是我尝试过但无法正常工作的内容: <?php /* Rate to chance. */ //max 10 decimals $rate = '0.010000000000'; //<-- should equal 1% chance $chance = $rate*pow(10,10); $random = mt_rand(

我想做的是(但完全弄糊涂了)在PHP中生成一个代码,它根据十进制数(最多10位小数)给出的概率执行代码,其中as 1是执行代码的100%概率。以下是我尝试过但无法正常工作的内容:

<?php
/*
    Rate to chance.
*/

//max 10 decimals
$rate = '0.010000000000'; //<-- should equal 1% chance

$chance = $rate*pow(10,10);

$random = mt_rand(0,pow(10,10));

if($random < $chance) { 
    echo "Ok."; //should be shown 1 out of 100 times in this example
}
?>

我之所以想这样做,是因为我希望代码执行的概率小于1%(例如0.001%)。我的代码(上面)不起作用,我可能做了一些相当愚蠢和完全错误的事情,但我希望其他人能帮助我,因为目前我完全困惑

提前谢谢

致以最良好的祝愿,
Skyfe.

pow
是一条错误的道路,它是
1/rate

<?php
// 1 chance out of 2, 50%
if (mt_rand(0, 1) === 0) {
   …
}
// 1 chance out of 101, which is < 1%
if (mt_rand(0, 100) === 0) {
    …
}

$rate = (double) '0.01';
$max = 1 / $rate; // 100
if (mt_rand(0, $max) === 0) {
    // chance < $rate
}

pow
是错误的选择,它是
1/rate

<?php
// 1 chance out of 2, 50%
if (mt_rand(0, 1) === 0) {
   …
}
// 1 chance out of 101, which is < 1%
if (mt_rand(0, 100) === 0) {
    …
}

$rate = (double) '0.01';
$max = 1 / $rate; // 100
if (mt_rand(0, $max) === 0) {
    // chance < $rate
}

当然了!谢谢你,我太蠢了>(谢谢!)编辑:有一个问题,如果$max是一个十进制值呢?(例如32.59)mt_rand本身只能返回整数,对吗?PHP将对其进行整型,就像您那样:
$max=(int)(1/$rate)通用机会计算器如何?请注意,这并不准确。如果美元汇率为0.5,我们希望2次中有1次机会。但是这给了mt_rand(0,2)==0,这是三分之一的机会。1%也是如此。mt_rand(01100)是101分之一的几率。@StephaneMombuleau这正是问题所在,几率必须小于
$rate
。我同意你的观点,这不是一个人应该如何处理概率。啊,当然!谢谢你,我太蠢了>(谢谢!)编辑:有一个问题,如果$max是一个十进制值呢?(例如32.59)mt_rand本身只能返回整数,对吗?PHP将对其进行整型,就像您那样:
$max=(int)(1/$rate)通用机会计算器如何?请注意,这并不准确。如果美元汇率为0.5,我们希望2次中有1次机会。但是这给了mt_rand(0,2)==0,这是三分之一的机会。1%也是如此。mt_rand(01100)是101分之一的几率。@StephaneMombuleau这正是问题所在,几率必须小于
$rate
。我同意你的观点,这不是一个人应该如何处理概率。