Seeding the random number generator in Javascript
是否有可能在Javascript中播种随机数发生器(Math.random)?
No, it is not, but it's fairly easy to write your own generator, or better yet use an existing one. Check out: this related question.
Also, see David Bau's blog for more information on seeding.
My other answer represents a more traditional algorithm, but I found Dave Scotese's comment to this answer to be a more eloquent one. Unfortunately, it's pretty slow due to string manipulation.
Here's a version that is about 20 times faster and a bit more precise as well.
var seed = 1;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
You can set seed
to be any number, just avoid zero (or any multiple of Math.PI).
The elegance of this solution, in my opinion, comes from the lack of any "magic" numbers (besides 10000, which represents about the minimum amount of digits you must throw away to avoid odd patterns - see results with values 10, 100, 1000). Brevity is also nice.
It's a bit slower than Math.random() (by a factor of 2 or 3), but I believe it's about as fast as any other solution written in JavaScript.
No, but here's a simple pseudorandom generator I adapted from Wikipedia:
var m_w = 123456789;
var m_z = 987654321;
var mask = 0xffffffff;
// Takes any integer
function seed(i) {
m_w = i;
m_z = 987654321;
}
// Returns number between 0 (inclusive) and 1.0 (exclusive),
// just like Math.random().
function random()
{
m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
var result = ((m_z << 16) + m_w) & mask;
result /= 4294967296;
return result + 0.5;
}
EDIT: fixed seed function by making it reset m_z
链接地址: http://www.djcxy.com/p/17726.html上一篇: 我如何永久启用IntelliJ中的行号?
下一篇: 在Javascript中播种随机数发生器