What is the precision of JavaScript's Math.random()
function?
Math.random()
generates a floating point number of 16 decimal places greater than or equal to zero and less than 1.
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));
111000000101010100010110011011110111000111010101110.1
sometimes. –
Eidolon 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.
Math.random()
in Javascript returns a floating point number in the range 0..1
, in the native javascript format, which is a 64 bit IEEE 754 double-precision floating point format. Due to the fact that this format uses 52 bits for the actual precision, you are effectively limited to 52 bits of precision in modern Javascript implementations.
In real usage (in base 10), this normally roughly translates into 15-16 digits. But, it can also be fewer decimal places if the number ends in zeroes.
If you are using a really ancient Javascript implementation (Internet Explorer, Safari from 2016 or Chrome from 2015 or some older out-of-life versions of Node), Math.random() may use an algorithm with only on a 32 bit precision, which means the last 20 bits of precision will just be 0, meaning you will get significantly less precision.
If you want more precision, you can use Crypto.getRandomValues(new BigUint64Array(1))
which will give you 64 bits of true precision using a verified CSPRNG algorithm.
© 2022 - 2024 — McMap. All rights reserved.