note 105452 added to function.rand
| From: | DanielKlein dot at osu1 dot php dot net | Date: | Fri, 19 Aug 2011 10:10:22 +0000 |
| Subject: | note 105452 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-182582@lists.php.net to get a copy of this message | ||
rand() has a granularity of getrandmax() which means that if you're on a Windows system where
getrandmax()==32767 then specifying a range greater than 0-32767 will still only give 32768 unique
values. Specifying min=0 and max > getrandmax()+1 where max == 2^n or max == 2^n-1 will return
numbers that are multiples of some 2^m where (getrandmax()+1) * 2^m == 2^n.
<?php
function gcd($x, $y) { // If gmp_gcd() is not available
for (;;) {
if ($x == 0) return $y;
else $y %= $x;
if ($y == 0) return $x;
else $x %= $y;
}
}
//$rand_max = 0xFFFFFE; // This gives 1
$rand_max = 0xFFFFFF; // This gives 512
$rand_max = 0x1000000; // This gives 512
//$rand_max = 0x1000001; // This gives 1
$gcd = rand(0, $rand_max);
for ($i = 0; $i < 1000; ++$i) {
$gcd = gcd($gcd, rand(0, $rand_max));
}
print($gcd);
?>
I would suggest always using mt_rand() instead as a good habit to get into.
----
Server IP: 117.55.229.1
Probable Submitter: 114.75.190.57
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/105452
Del: integrated -- https://master.php.net/note/delete/105452/integrated
Del: useless -- https://master.php.net/note/delete/105452/useless
Del: bad code -- https://master.php.net/note/delete/105452/bad+code
Del: spam -- https://master.php.net/note/delete/105452/spam
Del: non-english -- https://master.php.net/note/delete/105452/non-english
Del: in docs -- https://master.php.net/note/delete/105452/in+docs
Del: other reasons-- https://master.php.net/note/delete/105452
Reject -- https://master.php.net/note/reject/105452
Search -- https://master.php.net/manage/user-notes.php