phprandom

How to generate several random numbers included in a range and whose evolution is in a range in percent in PHP?


How to generate several random numbers included in a range and whose evolution is in a range in percent?

The goal is to generate random numbers while avoiding significant discrepancies.

i tried this code but with php 7.4, the random number only increases until I get a fatal error

$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);
}

Solution

  • Here is the solution

    $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);
    }