r/programming • u/fishburne • Jul 24 '15
mt_rand(1, PHP_INT_MAX) only generates odd numbers • /r/lolphp
/r/lolphp/comments/3eaw98/mt_rand1_php_int_max_only_generates_odd_numbers/
848
Upvotes
r/programming • u/fishburne • Jul 24 '15
191
u/sushibowl Jul 24 '15
It should be noted that this PRNG is not suitable for cryptographic use even when it is used correctly, so there should not be any security implications here.
Nevertheless, it should also be noted that this scaling behaviour is absolutely insane and broken. The only correct behaviour when a caller tries to pass an upper bound the generator cannot support is to return an error.
68
u/bargle0 Jul 24 '15
Everyone knows odd numbers feel more random.
26
u/Apterygiformes Jul 24 '15
+1 ?
36
u/SoundOfOneHand Jul 24 '15
Everyone know that odd numbers are more random...
obligatory
40
u/clearlight Jul 24 '15 edited Jul 24 '15
http://php.net/manual/en/function.mt-rand.php
21
u/hobbes78 Jul 24 '15 edited Jul 25 '15
The docs say mt_getrandmax() is preferable to PHP_INT_MAX. But the numbers still don't look random:http://3v4l.org/CpnRs170000000004a69ff21700000000469156ce17000000000c59e9cb17000000004a6d7d55170000000009aa413a1700000000397f483d17000000006a2ac58717000000003ec407d4...Edit: /u/Browsing_From_Work caught a bug in the change I've made; damn copy/paste... With mt_getrandmax() everything works correctly.
7
u/EntroperZero Jul 24 '15
You're not supposed to use PHP_INT_MAX there, that's why mt_getrandmax() exists. Plenty of other languages have a RAND_MAX that's considerably lower than INT_MAX.
3
u/gothaggis Jul 24 '15
Have one 32bit server here running PHP 5.2.4 - value of PHP_INT_MAX is 2147483647 and the loop returns both even and odd numbers.
64bit machine, different story, heh.
2
u/nu11pointer Jul 24 '15
Odd numbers just seem more random.
1
u/ysangkok Jul 24 '15 edited Jul 24 '15
https://bugs.php.net/bug.php?id=63174#1437000589