如何生成一个范围内的几个随机数,并且其演化在一个范围内(以百分比为单位)?
目标是生成随机数,同时避免显着差异。
我尝试了这段代码,但在 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);
}
解决方案在这里
$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);
}