Getting around the int limit of rand() and mt_rand().

Discussion in 'PHP' started by Submerged, May 24, 2010.

  1. #1
    Part of a script that I'm working on needs to call a random number from a theoretically extremely large maximum number (i.e., even upwards of 1,000^4).

    If I simply call a rand(1,x) or mt_rand(1,x), it actually starts sending back negative numbers (overflow).

    The actual line of code is simple (using 1000 as an example):

    $totalcount = 1000;
    $random = rand(1,pow($totalcount,4));

    Is there a way to either increase the maximum number to randomize or to work around it somehow?

    Thanks!
    - Submerged
     
    Submerged, May 24, 2010 IP
  2. Submerged

    Submerged Active Member

    Messages:
    132
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #2
    Hmmmm . . . I did find one possible solution:

    $totalcount = 1000;
    $random = mt_rand() / (double)mt_getrandmax()); // Gives a random decimal between 0 and 1
    $random = $random * bcpow("$totalcount",'4',2)); // Multiplies that decimal by the exponent -- i.e., gives a number between 1 and $totalcount^4, though with additional decimals.
    $random = ceil($rand); // Gets rid of extra decimals. Could also round() or floor() depending on purpose.

    This seems efficient enough, unless someone has something better?
     
    Submerged, May 24, 2010 IP
  3. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #3
    <?php
    
    $base	= 1000;
    $pow	= 12;
    $bpow	= bcpow($base, $pow);
    $len	= strlen($bpow);
    $rand	= substr(lcg_value(), 2);
    while(strlen($rand) < $len)
    {
    	$rand .= substr(lcg_value(), 2);
    }
    $rand = "0.$rand";
    
    echo bcmul($rand, $bpow, 0);
    echo PHP_EOL;
    
    ?>
    Code (markup):
     
    joebert, May 25, 2010 IP
  4. adamsinfo

    adamsinfo Greenhorn

    Messages:
    60
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    18
    #4
    define ("DESIRED_LENGTH", 50); //length of our random number
    $ctr = 0;
    $output = "";
    while ($ctr < DESIRED_LENGTH)
    {
    $output .= rand(0, 9);
    $ctr++;
    }
    echo $output;
     
    adamsinfo, May 25, 2010 IP
    Submerged likes this.
  5. Submerged

    Submerged Active Member

    Messages:
    132
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #5
    Haha . . . that is so simple it's brilliant :). Thanks!
     
    Submerged, Jun 8, 2010 IP