如何在PHP中生成一个范围内的多个随机数,并且其演变在一个百分比范围内?

问题描述 投票:0回答:1

如何生成一个范围内的几个随机数,并且其演化在一个范围内(以百分比为单位)?

目标是生成随机数,同时避免显着差异。

我尝试了这段代码,但在 php 7.4 中,随机数只会增加,直到出现致命错误

$min=400; // starting value
$max = 600; // starting value

for ($i = 1; $i <= 1000; $i++) 
{
    $nb = random_int($min, $max);

    echo $nb . "\n";

    $percentage_min = random_int(0, 10);
    $percentage_max = random_int(10, 20);

    $min = floor($nb-($nb * $percentage_min)/100);

    $max = floor($nb+($nb * $percentage_max)/100);
}
php random
1个回答
-1
投票

解决方案在这里

$min=0; // starting value
$max = 600; // starting value

$min_absolute = 100;
$max_absolute = 1000;

for ($i = 1; $i <= 2000; $i++) 
{
    if($max > $max_absolute)
    {
        $min = $min_absolute;
        $max = random_int($min_absolute, $max_absolute);
    }
    
    $nb = random_int($min, $max);

    echo $nb . "\n";

    $percentage_min = random_int(0, 10);
    $percentage_max = random_int(10, 20);

    $min = floor($nb-($nb * $percentage_min)/100);
    $max = floor($nb+($nb * $percentage_max)/100);
}
© www.soinside.com 2019 - 2024. All rights reserved.