Math.random()何时开始重复? [英] When does Math.random() start repeating?

查看:844
本文介绍了Math.random()何时开始重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nodejs中进行了这个简单的测试,我让它在一夜之间运行,无法重复Math.random()。我意识到迟早价值(甚至整个序列)都会重复,但对于什么时候会有什么合理的预期呢?

I have this simple test in nodejs, I left it running overnight and could not get Math.random() to repeat. I realize that sooner or later the values (or even the whole sequence) will repeat, but is there any reasonable expectancy as to when it is going to happen?

let v = {};
for (let i = 0;; i++) {
  let r = Math.random();
  if (r in v) break;
  v[r] = r;
}
console.log(i);


推荐答案

这是浏览器特定的:

https:// www.ecma-international.org/ecma-262/6.0/#sec-math.random


20.2 .2.27
Math.random()返回一个带有正号的数字值,大于或等于0但小于1,随机选择或伪
随机选择,在该范围内大致均匀分布,
使用依赖于实现的算法或策略。此函数
不带参数。

20.2.2.27 Math.random ( ) Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.

为不同的代码创建的每个Math.random函数必须
从连续调用生成不同的值序列。

Each Math.random function created for distinct code Realms must produce a distinct sequence of values from successive calls.

此处的要求只是伪随机且均匀分布。

The requirement here is just pseudo-random with uniform distribution.

这是来自V8(Chrome和NodeJs的Javascript引擎)的博客文章。

Here's a blog post from V8 (Chrome and NodeJs's Javascript Engine).

https://v8.dev/blog / math-random

他们说他们在使用 xorshift128 + ,其最大周期为 2 ^ 128 -1

Where they say they are using xorshift128+, which has a maximal period of 2^128 -1.

这篇关于Math.random()何时开始重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆