Math.random()如何在javascript中工作? [英] How does Math.random() work in javascript?
问题描述
我最近想出了如何通过谷歌获取一个随机数,它让我想到 Math.random()
是如何工作的。所以在这里,我无法弄清楚他们是如何做Math.random()的,除非他们使用时间之类的东西,任何人都知道JavaScript的 Math.random()
是如何运作的等价?
I recently figured out how to get a random number via google, and it got me thinking how does Math.random()
work. So here I am I can not figure out how they did Math.random() unless they used a time like thing does anyone know how JavaScript's Math.random()
works or an equivalent?
推荐答案
Math.random()返回一个带有正号的Number值,大于或等于0但小于1 ,使用依赖于实现的算法或策略随机或伪随机地选择在该范围内具有近似均匀分布。
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.
这是V8的实现:
uint32_t V8::Random() {
// Random number generator using George Marsaglia's MWC algorithm.
static uint32_t hi = 0;
static uint32_t lo = 0;
// Initialize seed using the system random(). If one of the seeds
// should ever become zero again, or if random() returns zero, we
// avoid getting stuck with zero bits in hi or lo by reinitializing
// them on demand.
if (hi == 0) hi = random();
if (lo == 0) lo = random();
// Mix the bits.
hi = 36969 * (hi & 0xFFFF) + (hi >> 16);
lo = 18273 * (lo & 0xFFFF) + (lo >> 16);
return (hi << 16) + (lo & 0xFFFF);
}
以下是StackOverflow上的几个相关主题:
Here are a couple of related thread on StackOverflow:
- Why is Google Chrome's Math.random number generator not *that* random?
- How random is JavaScript's Math.random?
这篇关于Math.random()如何在javascript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!