PHP 随机数混乱

发布于 2024-10-18 06:51:00 字数 147 浏览 7 评论 0原文

假设我有 2 个小数位数(例如 0.75 和 0.25)。我正在尝试创建一个函数,获取这两个数字并根据这两个数字的百分比随机选择一个“获胜者”。简而言之,我需要 0.75 号码比 0.25 号码有更好的机会被选中(0.25 仍然可以被选中,但只有 25% 的机会)。我该怎么做呢?

So lets say I have 2 numbers in decimals (eg .75 and .25). I am trying to make a function that gets these 2 numbers and chooses a "winner" randomly but based on those 2 numbers' percentages. In short terms, I need the .75 number to have a better chance at getting picked then the .25 number (the .25 can still get picked, but it has only a 25% chance). How should I go about doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

溺深海 2024-10-25 06:51:01

如果它们的总和不总是为 1,这仍然有效:

$winner = ( (rand(0,1000) / 1000) <= ($first / ($first + $second)) ) ? $first : $second;

If they don't always add up to 1, this will still work:

$winner = ( (rand(0,1000) / 1000) <= ($first / ($first + $second)) ) ? $first : $second;
甜`诱少女 2024-10-25 06:51:01
$var1 = 25;
$var2 = 75;
$total = $var1 + $var2;

$rand = mt_rand(1, $total);

if($rand <= $var1)
    echo("Value one ({$var1}) Wins!");
else
    echo("Value two ({$var2}) Wins!");

类似的东西应该有效。

$var1 = 25;
$var2 = 75;
$total = $var1 + $var2;

$rand = mt_rand(1, $total);

if($rand <= $var1)
    echo("Value one ({$var1}) Wins!");
else
    echo("Value two ({$var2}) Wins!");

Something like that should work.

沒落の蓅哖 2024-10-25 06:51:01

在这种简单的情况下,您可以使用:

 if (rand(0,1000)/1000 <= 0.25)
 {
     $winner = $first;   // 25% number
 }
 else {
     $winner = $second;  // 75% number
 }

In this simplistic case you could use:

 if (rand(0,1000)/1000 <= 0.25)
 {
     $winner = $first;   // 25% number
 }
 else {
     $winner = $second;  // 75% number
 }
昵称有卵用 2024-10-25 06:51:00
$prob = array(25, 75);

$total = array_sum($prob);

$rand = mt_rand(1, $total);

var_dump($rand);

foreach ($prob as $i => $p) {
    $rand -= $p;

    if ($rand <= 0) {
        $winner = $i;
        break;
    }
}

var_dump($winner);
$prob = array(25, 75);

$total = array_sum($prob);

$rand = mt_rand(1, $total);

var_dump($rand);

foreach ($prob as $i => $p) {
    $rand -= $p;

    if ($rand <= 0) {
        $winner = $i;
        break;
    }
}

var_dump($winner);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文