10 ms·
A call to PHP's mt_rand generates only odd numbers
- beefhash 11y agoUsing a loop of that length (for ($i=0;$i<10000;$i++)) on a site allowing people to execute code, and then linking it to HN effectively amounts to a do-it-yourself DDoS. I don't think I wanna be the host of that site right now.
- deanclatworthy 11y ago... and it's down :) I guess they get this all the time.
- laumars 11y agoThe site itself picked up on this aswell. The following message appeared for me: "Abusive script This script was stopped while abusing our resources" edit: Too slow: 504 Gateway Time-out
- Xlab 11y agoThey don't even caution about it.
- the-dude 11y agoWhich we could call 'suiciDDOS'
- _asummers 11y agoIt's also being linked on Reddit for a double whammy DDoS.
- Buge 11y agoShouldn't they cache the result?
- Stormcaller 11y agoBecause max value should be "mt_getrandmax()" instead of "PHP_INT_MAX", it just gets a 32 bit number then scales it up. see: http://php.net/manual/en/function.mt-rand.php http://php.net/manual/en/function.mt-rand.php Under caution: The distribution of mt_rand() return values is biased towards even numbers on 64-bit builds of PHP when max is beyond 2^32. This is because if max is greater than the value returned by mt_getrandmax(), the output of the random number generator must be scaled up. edit: this post went from 5 points to 1, which I don't care about(in ~500 days I posted less than 10 times and I have ~35 points), but who downvotes documentation, seriously? -_-
- 3JPLW 11y agoWhy even accept ranges that span more than 2^32? That seems like an easy solution to a broken function. Also fun: echo "<?php echo mt_rand(-mt_getrandmax(), mt_getrandmax());" | php is always even on my PHP 5.5.20.
- poizan42 11y agoWhy not generate two values from the underlying function and shift them into place if the range is larger than 2^32 -1? Oh well, ofc. because this is PHP which goes by the principle of most surprise.
- TillE 11y agoYes, that's exactly what sensible RNG interfaces do, like std::random in C++. If your underlying engine only produces 32 bits at a time, it'll grab two of them when you request a 64-bit type.
- TazeTSchnitzel 11y ago> Why even accept ranges that span more than 2^32? That seems like an easy solution to a broken function. It may never have been designed to. If it was written before 64-bit machines were commonplace, mt_getrandmax() would always be the same as PHP_INT_MAX.
- 11y ago
- deleted 11y ago[deleted]
- deleted 11y ago[deleted]
- mercuti0 11y agoYou on a 32-bit system?
- 3JPLW 11y agoGiven that all the numbers are less than 2^32, there's less than a 10^-192 chance that it's a 64 bit system...
- foxhill 11y agofor reference, the estimated probability that a proton will spontaneously decay into a neutron in a second is ~4.1x10^-37. this has never been observed.
- Retra 11y agoTo be fair, we aren't looking that hard...
- marcosdumay 11y agoNeutrino detectors should detect neutron decay, shouldn't they? If so, we are looking very hard.
- Retra 11y agoYou can't set up one or three neutrino detectors for something that improbable and call it a serious effort.
- marcosdumay 11y agoDo they need setting? I imagined they'd detect one by themselves, without any tunning. But then, 10^-37 is a very low number. I wouldn't be surprised if that means that all neutrino detectors could catch one, but failed to do so up to now.
- deckiedan 11y agoIt's because there simply are more odd numbers than even numbers... (j/k!)
- raverbashing 11y agoI think if you consider Z rather than N the opposite is true Proof: For ever number k there exists -k which has the same parity as k (that is, if k is even, -k is even as well) For every k there is (k + 1) with opposite parity (same thing with -k and -(k + 1) Now, if we count the numbers, from 1 to infinite, the number of even and odd numbers is the same from 1 to -infinite the number of even and odd numbers is the same as well And you get an extra zero, an even number
- seanyeh 11y agoTechnically, you can create a bijection between all natural numbers and all even numbers. For all natural numbers k, there is an even number 2k (and for every even number 2k, there is a natural number k). So, the number of even numbers and natural numbers is the same. That's what happens when you try to reason with infinity ;)
- raverbashing 11y agoYes, with Natural numbers Curious what is possible in Integer numbers > That's what happens when you try to reason with infinity ;) Ah yes! Fascinating subject
- greiskul 11y agoCardinality of natural numbers and integers is also the same. 0 -1 1 -2 2 -3 3... 0 1 2 3 4 5 6...
- greydius 11y agoCount from 2 to infinity and 0 to -infinity and you will get the opposite result: you'll have an extra odd number, 1.
- sarciszewski 11y agoAnd that's another reason why it's a good thing that PHP 7 (coming out soon!) has a new function called random_int() which provides an unbiased distribution of integers powered by a CSPRNG (yes, it uses urandom, in case anyone asks). My employer is leading the effort to expose a compatible interface in PHP 5 applications so developers can add one line to their composer.json file and start writing code for PHP 7. It's MIT licensed and should nearing its 1.0.0 release soon. https://github.com/paragonie/random_compat https://github.com/paragonie/random_compat
- rurban 11y agoUsing /dev/urandom is not a good thing. It's only needed to get secure random numbers (CSPRGs) very slowly. You'll drain it so that the apps which really need it will be out of seeds. To get random numbers fast, you need to use the good bits of a PRG based on an LCG. Everybody should know by now that the mersenne twister is not only bad, but also slow. Everybody should know by now that the first bits are good, and the last bits horrible. That's why you should not use modulo %, but rshift or better use Melissa E. O'Neill's PCG, which uses the first good bits to improve the latter worse bits. http://www.pcg-random.org/ http://www.pcg-random.org/
- sarciszewski 11y ago> Using /dev/urandom is not a good thing. It's only needed to get secure random numbers (CSPRGs) very slowly. https://gist.github.com/sarciszewski/f7bd4c0358a44321787b https://gist.github.com/sarciszewski/f7bd4c0358a44321787b http://3v4l.org/j330O http://3v4l.org/j330O mt_rand() performs worse than CSPRNGs, funny enough Using a strong PRF we can take a 128-bit seed and turn it into an endless stream of random numbers. If /dev/urandom drains entropy, that's a bug that your OS should fix. > Everybody should know by now that the first bits are good, and the last bits horrible. That's why you should not use modulo %, but rshift or better use Melissa E. O'Neill's PCG, which uses the first good bits to improve the latter worse bits. http://www.pcg-random.org/ http://www.pcg-random.org/ Yeah, there is no pgc_random() function in PHP though.
- 11y ago
- dantillberg 11y agoI believe it's also generally an anti-pattern to do things like "num = rand() % max" or "num = rand() & bit_mask" where rand() returns an integer from a pseudo-random number generator, right? PHP may not do a very good job at ensuring an even distribution throughout the space of possible integers, but for PRNGs in general (especially the quick & dirty ones), the worst place to grab bits from is the least-significant bits. (my source is that I hung out with a copy of Numerical Recipes in college; Numerical Recipes has a nice chapter for learning about PRNGs, along with example code for a number of implementations)
- sarciszewski 11y agoYes, don't use % even with a CSPRNG! https://stackoverflow.com/a/31374501/2224584 https://stackoverflow.com/a/31374501/2224584
- tptacek 11y agoIt's true that's an anti-pattern, but it's not a particularly exploitable one in most of the places that really need CSPRNGs.
- paragon_init 11y agoAgreed. It's a red flag for "expect more exploitable issues to be found around the corner" and can result in biased distributions, but it by itself does not break a RNG.
- lucb1e 11y agoOh? I get perfectly sane results using modulo, as it should if it is actually a completely random number: http://3v4l.org/nIBGT http://3v4l.org/nIBGT
- sarciszewski 11y agoYou found the exception! Congratulations! You're using a bucket size which is a power of 2. A random byte fits on the interval of [0, 255] which is evenly distributed modulo 256, which if you reduce mod 2^N for 1 < N < 8 will still produce a uniform distribution. If you copied my JS code into your console and changed the 54 to 64 the bias evaporates. Hooray :D However, for arbitrary ranges, you should use an unbiased selection strategy to ensure a uniform distribution. http://3v4l.org/EgfPR http://3v4l.org/EgfPR - notice 0 is significantly more common than the other values when reduced mod 17 http://3v4l.org/LXmKq http://3v4l.org/LXmKq - same with mod 15 https://defuse.ca/generating-random-passwords.htm https://defuse.ca/generating-random-passwords.htm
- T3RMINATED 11y agoAbusive script This script was stopped while abusing our resources
- T3RMINATED 11y agoAbusive script This script was stopped while abusing our resources
- MrDosu 11y agoThis is why you read the documentation. Don't deduce what a method does purely on its name and your common sense, you are probably wrong...
- noir_lord 11y agoI use PHP a lot (primary product is written in it) and I actually mostly like using it but you can get really burnt applying the "principle of least surprise" to the PHP standard library. I really wish there was more support behind the idea of creating a new standard library and gradually deprecating the old one, it's been tried but never gets any traction. Meanwhile frameworks and libraries continue to add their own (often very good) helper libraries to smooth the edges.
- pogden 11y agoAt least in PHP. Unfortunately in my experience the PHP documentation is not frequently read by PHP developers or even PHP internals developers. It seems to exist mainly for PHP hatebloggers, for whom it's a gold mine. This illustrates some problems with the PHP way of doing things. For some reason the PHP internals community prefers to have this function continue to spit out garbage when given invalid inputs instead of throwing an error, especially if spitting out garbage is what was done in the past. The answer is always, "Don't do that. RTFM." but most developers don't read the documentation for each and every function that they use, but rather rely on the name of and common sense until there's a error. If there's no error, the documentation never gets read.
- TelmoMenezes 11y agoYes. In fact I propose that giving methods pronounceable names is an anti-pattern. Method names should be random strings of characters. Then you don't fall into the temptation of not reading the documentation and assuming things. In fact, make them long enough so that you can't memorize them. someObj.dbrdCfj34uW31U289u(x) This avoids a lot of frustration. Imagine if this was called someObj.sqrt(x). People could jump to the conclusion that this takes the square root of a value, when in reality it only does so on weekdays. On weekends it returns the CPU temperature.
- _yy 11y agoQuoting a Reddit comment (https://www.reddit.com/r/lolphp/comments/3eaw98/mt_rand1_php_int_max_only_generates_odd_numbers/ https://www.reddit.com/r/lolphp/comments/3eaw98/mt_rand1_php...): The problem is way worse than you think. Check out what this looks like when printed in hexadecimal: http://3v4l.org/XVTgS http://3v4l.org/XVTgS Basically, what is going on is that PHP_INT_MAX is 2^63 - 1. mt_getrandmax() is 2^31 - 1. The way mt_rand() makes a random number when the limit is too large is that it makes a random number in the range [0,2^(31)), then it scales it to be a number in the range [0,MAX-MIN), and finally adds MIN. So in your case, it scales everything by 2^32 and adds 1. Which is why the numbers are* extremely non-random. [See my other comment in this thread for a more detailed explanation and some more test scripts that prove this is what is happening.](https://www.reddit.com/r/lolphp/comments/3eaw98/mt_rand1_php_int_max_only_generates_odd_numbers/ctdhxha)* https://www.reddit.com/r/lolphp/comments/3eaw98/mt_rand1_php...
- deleted 11y ago[deleted]
- InfiniteEntropy 11y agoI see your problem, PHP.