What is the max value that Math.random can produce?

Viewed 553

While using Math.random of javascript, I came across a interesting question.

According to the docs, it produces a "pseudo-random number in the range 0 to less than 1", but what is the biggest number, less than 1 it can produce?

I made this silly code to try getting the highest value

maxIteration = 1000000000
value = 0
count = 0
while(value < 1 && count++ < maxIteration) {
    let newValue = Math.random()
    value = value < newValue ? newValue : value
}
console.log('value', value)
console.log('count', count)

The highest I could get is 0.9999999989486876, but is it the highest?

2 Answers

What is the max value that Math.random can produce?

The documentation fails to state that, both the Mozilla documentation you point to and the ECMAScript Language Specification (2020 version at time of writing).

The maximum value less than 1 that the Number type can represent is 1−2−53. (This value occurs when all 53 bits of the significand are ones and the exponent is −1, giving the value +1.111…1112•2−1 = 1−2−53.) Ideally, that would be the maximum value Math.random returns, but the documentation does not say so.

You can check the docs for numbers to understand the float point details.

TLDR: Number type is a double-precision 64-bit binary format IEEE 754 value. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding.

var minValue = Number.MIN_VALUE; // 5e-324
// (1 - minValue) == 1

var maxRandom = 1 - 10e-17; // ~= as 1 - (2e-53)

document.body.innerHTML = 'Number.MIN_VALUE = '+ minValue + '<br>maxRandom = ' + maxRandom;

Related