【发布时间】:2020-02-02 00:48:28
【问题描述】:
我正在阅读随机数生成器并在 javascript 中调整了 xorShift128+ 算法的实现。我了解位移运算符的工作原理以及异或位运算的工作原理,尽管我仍在学习它们为什么有用,以及为什么它们在 xorShift128+ 中的使用会产生均匀的随机分布。
但更重要的是,我只需要知道它使用的可能数字的范围是多少。它输出整数,我试图获得 0 到 1 之间的数字。归纳起来,我看到它的顺序是 2**32。所以我用它作为除数。但是,当我检查一致性时,我注意到数字存在偏差。它们似乎在 0.2 = 0.7 的区域内被排斥。
所以我要么校准除数错误,要么我的实现错误,或者我对均匀性属性感到困惑。任何帮助,将不胜感激。下面是我的代码和我的分析:
function xorShift128p(seed) {
// seeds
this.x = seed || this.x || 1;
this.y = seed + 1 || this.y || 2;
// swap seeds
let x = this.y;
let y = this.x;
// bit manipulations that are still a little
// obscure to me as to why they work well
y ^= y << 23;
y ^= y >> 17;
y ^= x;
y ^= x >> 26;
// reset seeds
this.x = x;
this.y = y;
// output, with calibration for 0-1 range.
let realResult = x + y;
let myCalibration = realResult / (2**32);
return myCalibration;
}
// produce an array of 100 random numbers using xorShift128p
let rands =
[...new Array(100).keys()]
.map(() => xorShift128p());
// bin the random numbers into units of 0.1
let binCounts =
[...new Array(10).keys()]
.map(key =>
`lead: ${(key / 10).toFixed(1)}, ` +
`count: ${rands.filter(r => r >= key / 10 && r < (key + 1) / 10).length}`
);
// notice the non-uniformity
console.log(binCounts);
【问题讨论】:
标签: javascript algorithm random