PHP rate to chance for event to happen

泄露秘密 提交于 2019-12-11 11:29:52

问题


What I'm trying to do ( but getting totally confused with ) is to make a code in PHP that executes a code based on a chance that's given in decimal numbers (10 decimals max) where as 1 would be 100% chance for the code to be executed. Here's what I tried but is not working properly:

<?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
}
?>

Why I want to make this work is because I'd like to have a code executed with a chance of smaller than 1% (e.g. 0.001%). My code ( above ) isn't working and I'm probably doing something pretty stupidly and totally wrong but I hope someone else can help me out because currently I'm totally confused.

Thanks in advance.

Best Regards, Skyfe.


回答1:


pow is the wrong way to go, it's 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
}


来源:https://stackoverflow.com/questions/8833895/php-rate-to-chance-for-event-to-happen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!