Math.random() 如何在 javascript 中工作? [英] How does Math.random() work in javascript?
问题描述
我最近想出了如何通过 google 获取随机数,这让我开始思考 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 a 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 threads on StackOverflow:
这篇关于Math.random() 如何在 javascript 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!