要測試 JavaScript 隨機數生成器的均勻性,您可以使用以下方法:
以下是一個簡單的示例,用于測試 JavaScript 的 Math.random()
隨機數生成器的均勻性:
function testRandomness(iterations) {
const counts = new Array(10).fill(0);
for (let i = 0; i < iterations; i++) {
const randomValue = Math.floor(Math.random() * 10);
counts[randomValue]++;
}
const expectedCount = iterations / 10;
const tolerance = iterations / 1000; // 設置一個容差值
for (let i = 0; i < counts.length; i++) {
const count = counts[i];
const deviation = Math.abs(count - expectedCount);
if (deviation > tolerance) {
console.log(`Value ${i} appears ${count} times, which is ${deviation.toFixed(
2
)} times more frequently than expected.`);
} else {
console.log(`Value ${i} appears ${count} times, which is within ${tolerance.toFixed(
2
)} times the expected count.`);
}
}
}
// 使用 10000 次迭代測試隨機性
testRandomness(10000);
這個函數會生成 10 個范圍內的隨機整數(0 到 9),并統計每個整數出現的次數。然后,它會檢查每個整數的出現次數是否在預期范圍內。您可以根據需要調整 iterations
和 tolerance
參數。
請注意,Math.random()
生成的是偽隨機數,因此在某些情況下可能無法完美地均勻分布。對于需要高質量隨機數的應用,建議使用 Web Crypto API 或其他加密安全的隨機數生成器。