问题
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