Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 18005

Why are random integers generated by multiplying by MAX_SAFE_INTEGER not evenly distributed between odd and even?

$
0
0

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

Viewing all articles
Browse latest Browse all 18005


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>