Trying to generate a number using MAX_SAFE_INTEGER I noticed something strange, I'm sure it has to do with the way numbers are stored in JavaScript, but I don't understand what exactly it is.
// Always returns an odd numberMath.floor(Math.random() * Number.MAX_SAFE_INTEGER)// Returns an odd number 75% of the timeMath.floor(Math.random() * (Number.MAX_SAFE_INTEGER - 1))// Has a 50/50 chance to return odd or evenMath.ceil(Math.random() * Number.MAX_SAFE_INTEGER)
How can this behavior be explained and what would be the largest integer you can use in Math.floor
to get a 50/50 ratio?
let evenCount = 0, oddCount = 0;for (let i = 0; i < 10000; i++) { const randomNumber = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); if (randomNumber % 2 === 0) { evenCount++; } else { oddCount++; }}console.log("Number of even numbers:", evenCount);console.log("Number of odd numbers:", oddCount);