What is the precision of JavaScript's Math.random() function?
-
1`Math.random()` is the correct function. – tcooc Jul 27 '10 at 14:10
-
1Right, that's what I meant. Thanks! – jpc826 Jul 27 '10 at 14:24
3 Answers
It's browser/JavaScript engine dependent.
The maximum possible precision is 52 bits, because Math.random returns a double-precision floating-point between 0 (inclusive) and 1 (exclusive). This maximum corresponds to roughly 16 decimals, see Sly1024's answer.
In practice, many browsers give a smaller precision. This seems to be the current state:
- Firefox: the full 52 random bits.
- V8/Chrome: 32 bits precision (some years ago it used to be as low as 30 bits, see https://codereview.chromium.org/1599019)
- Safari: 32 bits
- IE: ?
Run the following piece of code several times and you'll see that the trailing 21 bits are consistently 0 in Chrome and Safari.
console.log((Math.random() * Math.pow(2,53)).toString(2));
- 101
- 1
- 5
-
IE11: 52 random bits, although the code above gives results like `111000000101010100010110011011110111000111010101110.1` sometimes. – Andrew Morton Jan 15 '17 at 16:58
-
Chrome seems to have upgraded their precision, I can no longer observe the 21 consistently 0 bits. – Daniel Vestøl Aug 11 '19 at 16:25
-
Chrome (and in extension, all Blink-based browsers and V8-based products, such as Electron-apps and Node.js) updated the Math.random() precision to 128 bits in 2015. – Aron Cederholm Sep 04 '20 at 07:55
Math.random() generates a floating point number of 16 decimal places greater than or equal to zero and less than 1.
-
6Javascript floating point numbers are 64-bit IEEE 754 values, so it's not *exactly* 16 decimal places. – Pointy Jul 27 '10 at 14:16
-
-
-
According to wikipedia : Double-precision floating-point format the fraction part is 52 bits, and we know that the number will be between 0 and 1 (I think not including 1), so the exponent is -1, that leaves us with 52 random bits.
The 52 random bits give you 52 bit precision, which in base 10 is about
52*log10(2) ~= 15.653559774527022151114422525674 digits.