Math.random 生成多少熵?

2024-05-04

我想生成一个非常大的随机数。我不需要这个号码来保证加密安全。因此,我没有使用crypto.getRandomValues https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues。目前,我正在生成随机数,如下所示:

const random = length =>
    Math.floor(length * Math.random());

const padding = (length, character, string) =>
    (new Array(length + 1).join(character) + string).slice(string.length);

const randomBits = bits =>
    padding(bits, '0', random(Math.pow(2, bits)).toString(2));

const getRandom = bits =>
    bits <= 32 ? randomBits(bits) : randomBits(32) + getRandom(bits - 32);

console.log('         1         2         3         4         5         6');
console.log(getRandom(64));

然而,这似乎有点浪费,因为 JavaScript 中的数字是64位长 https://en.wikipedia.org/wiki/Double-precision_floating-point_format:

在我看来,我们至少应该能够恢复尾数的所有 52 位。我们可以从生成的数字中提取多少位熵Math.random在 JavaScript 中,又如何?


确定性算法(包括伪随机数生成器)本身无法生成熵;它必须来自外部,例如算法接收的种子。

但请注意,ECMAScript 规范Math.random() https://stackoverflow.com/questions/53002023/when-does-math-random-start-repeating允许实现使用任何“依赖于实现的算法或策略”,不一定是确定性算法,只要数字是“随机或伪随机选择的,在区间 [0, 1) 上近似均匀分布”。因此,无论Math.random()实际上使用熵同样依赖于实现——也没有强制要求收集熵来为 PRNG 播种的特定策略(如果实现使用一个策略)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Math.random 生成多少熵? 的相关文章

随机推荐