14

What is the precision of JavaScript's Math.random() function?

Cœur
  • 34,719
  • 24
  • 185
  • 251
jpc826
  • 235
  • 2
  • 8

3 Answers3

10

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:

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));

themaarten
  • 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
10

Math.random() generates a floating point number of 16 decimal places greater than or equal to zero and less than 1.

James
  • 106,638
  • 30
  • 159
  • 173
krs1
  • 1,105
  • 7
  • 16
3

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.
Kaalras
  • 1,063
  • 10
  • 13
Sly1024
  • 359
  • 3
  • 2