I ran into an odd "bug" today when I was running some unit tests in various browsers. I had run the tests in Firefox many times before today, and even IE but apparently not Chrome (v19-dev) yet. When I ran them in Chrome it consistently failed one test because two values I was calculating did not match.
When I really dug into what was happening I realized that the issue was that I was assuming that if I filled an array with 100,000 Math.random()
values that they would all be unique (there wouldn't be any collisions). Turned out that in Chrome that is not true.
In Chrome I was consistently getting at least two pairs of values that matched out of 100,000. Firefox and IE9 never experience a collision. Here is a jsfiddle I wrote just for testing this that creates 1M Math.random()
entries in an array: http://jsfiddle.net/pseudosavant/bcduj/
Does anyone know why the Chrome pseudo-random number generator that is used for Math.random
is really not that random? It seems like this could have implications for any client-side js encryption routines that ever use Math.random
.
Math.random()
generates a double-precision floating-point number, but the OP's test for equality works by converting those numbers to strings first, so unless the browser decides to include more than fifteen places past the decimal in its string representations, the OP is comparing values with much less entropy than that. – Cassette100.0
and100.1
. Between0.0
and1.0
, there are about 2-to-the-power-of-62 double-precision floating-point numbers. – Cassette5555555.5555555555555
might include a similar number of significant figures, and fewer places past the decimal-point, than stringification of5.5555555555555
. – CassetteMath.random().toString()
is usually 18 digits +/- 1 in my jsfiddle. That is characters, not digits, since it includes the.
in the string length. So usually 17 digits of numbers, which will go as high as 999 quadrillion. Still shouldn't have 2 sets of collisions per 100,000. – MiloreMath.random()
entries there are consistently still more than 100 non-unique pairs of numbers. – Milore