尝试使用 MAX_SAFE_INTEGER 生成数字时,我注意到一些奇怪的事情,我确信这与数字在 javascript 中存储的方式有关,但我不明白它到底是什么。
Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) // Always returns an odd number
Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER - 1)) // Returns an odd number 75% of the time
Math.ceil(Math.random() * Number.MAX_SAFE_INTEGER) // Has a 50/50 chance to return odd or even
如何解释这种行为以及在 Math.floor 中可以使用的最大整数是多少来获得 50/50 比率?
class RandomNumberCounter {
constructor() {
this.evenCount = 0;
this.oddCount = 0;
}
generateNumbersAndCount() {
for (let i = 0; i < 10000; i++) {
const randomNumber = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
if (randomNumber % 2 === 0) {
this.evenCount++;
} else {
this.oddCount++;
}
}
}
printCounts() {
console.log("Number of even numbers:", this.evenCount);
console.log("Number of odd numbers:", this.oddCount);
}
}
const randomNumberCounter = new RandomNumberCounter();
randomNumberCounter.generateNumbersAndCount();
randomNumberCounter.printCounts();
class RandomNumberCounter {
constructor() {
this.evenCount = 0;
this.oddCount = 0;
}
generateNumbersAndCount() {
for (let i = 0; i < 10000; i++) {
// Changed
const randomNumber = Math.floor(
Number.MAX_SAFE_INTEGER * (3 * (Math.random() - 0.5))
);
if (randomNumber % 2 === 0) {
this.evenCount++;
} else {
this.oddCount++;
}
}
}
printCounts() {
console.log("Number of even numbers:", this.evenCount);
console.log("Number of odd numbers:", this.oddCount);
}
}
const randomNumberCounter = new RandomNumberCounter();
randomNumberCounter.generateNumbersAndCount();
randomNumberCounter.printCounts();