In PHP, how do I generate a big pseudo-random number?

前端 未结 14 1144
遇见更好的自我
遇见更好的自我 2020-12-03 14:12

I\'m looking for a way to generate a big random number with PHP, something like:

mt_rand($lower, $upper);

The closer I\'ve

相关标签:
14条回答
  • 2020-12-03 15:02

    This question was asked like decade ago but for folks that come from Google propper answer is gmp_random_range("min_value", "max_value") funciton.

    $range=gmp_random_range("1225468798745475454898787465154", "1225468798745475454898787465200");
    echo gmp_strval($range); // displays value as string
    
    0 讨论(0)
  • 2020-12-03 15:03

    What you really need to know is the relative gap; if it's small then you can generate a number from 0 to the maximum gap then add the minimum to that.

    0 讨论(0)
  • 2020-12-03 15:09

    What you can do is create a few smaller random numbers and combine them. Not sure on how large you actually need though.

    0 讨论(0)
  • 2020-12-03 15:09

    Tested and works

    <?php 
    
    $min = "1225468798745475454898787465154";
    $max = "1225468798745475454898787465200";
    
    $bigRandNum = bigRandomNumber($min,$max);
    echo "The Big Random Number is: ".$bigRandNum."<br />";
    
    function bigRandomNumber($min,$max) {
        // take the max number length
        $number_length = strlen($max);
    
        // Set the counter
        $i = 1;
    
        // Find the base and the min and max ranges
        // Loop through the min to find the base number
        while ($i <= $number_length) {
            $sub_string = substr($min, 0, $i);
    
            // format pattern
            $format_pattern = '/'.$sub_string.'/';
            if (!preg_match($format_pattern, $max)) {
                $base = $sub_string;
    
                // Set the min and max ranges
                $minRange = substr($min, ($i - 1), $number_length);
                $maxRange = substr($max, ($i - 1), $number_length);
    
                // End while loop, we found the base
                $i = $number_length;
            }
            $i++;
        }
        // find a random number with the min and max range
        $rand = rand($minRange, $maxRange);
    
        // add the base number to the random number
        $randWithBase = $base.$rand;
    
        return $randWithBase;
    }
    
    ?>
    
    0 讨论(0)
  • 2020-12-03 15:10
    $lower = gmp_com("1225468798745475454898787465154");
    $upper = gmp_com("1225468798745475454898787465200");
    
    $range_size = gmp_sub($upper, $lower);
    
    $rand = gmp_random(31);
    $rand = gmp_mod($rand, $range_size);
    
    $result = gmp_add($rand, $lower);
    

    Totally untested :-)

    0 讨论(0)
  • 2020-12-03 15:14

    Take your floor and and your random number in the range to it.

    1225468798745475454898787465154 + rand(0, 6)
    
    0 讨论(0)
提交回复
热议问题