PHP 率与事件发生的机会 [英] PHP rate to chance for event to happen

查看:50
本文介绍了PHP 率与事件发生的机会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做的(但完全混淆)是在 PHP 中创建一个代码,该代码根据以十进制数(最多 10 个小数)给出的机会执行代码,其中 1 是 100% 的机会用于要执行的代码.这是我尝试过但无法正常工作的内容:

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

为什么我要完成这项工作是因为我希望代码执行的几率小于 1%(例如 0.001%).我的代码(上面)不起作用,我可能在做一些非常愚蠢且完全错误的事情,但我希望其他人可以帮助我,因为目前我完全困惑.

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.

提前致谢.

最好的问候,Skyfe.

Best Regards, 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
}

这篇关于PHP 率与事件发生的机会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆