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
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?
<?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):
define ("DESIRED_LENGTH", 50); //length of our random number $ctr = 0; $output = ""; while ($ctr < DESIRED_LENGTH) { $output .= rand(0, 9); $ctr++; } echo $output;