# JS随机数生成算法

——————————————

http://www.zhihu.com/question/22818104

——————————————

```function rnd( seed ){
seed = ( seed * 9301 + 49297 ) % 233280; //为何使用这三个数?
return seed / ( 233280.0 );
};

function rand(number){
today = new Date();
seed = today.getTime();
return Math.ceil( rnd( seed ) * number );
};

myNum=(rand(5)); Google了一下这3个数字，一些说法也是人云亦云没有找到合理的解释。例如:Generate Repeatable Random Numbers (in JS)```

Why ‘(seed * 9301 + 49297) % 233280‘ ?!

The answer is both simple&complicated: The combination of 9301, 49297 and 233280 provide a very even distributed set of “random” numbers. Please don’t ask WHY – that’s the complicated part, some very smart people figured out those numbers quite some time ago, and I also cannot tell you how they did it.

`很聪明的前人算出来的？。。。=============================================================又找到一个页面 http://www.ict.griffith.edu.au/anthony/info/C/RandomNumbers 好像有列举，但是没能看懂，ACM之类的。。，有人能解释下不？`
``````Simple (bad) Psuedo Random Number Generator (Sic)
The low bit typically just toggles between calls.

random() {
seed = ( seed * mulitiplier + increment ) % modulus;
return seed;
}

Table of Good values
Multiplier    Increment     Modulus
25173         13849        65536
9301         49297       233280``````
`=+=+=+=+=+=+=+=+=+=+=+=+==+=+=+=+=+=+=+=+=+=+=+=+= 简陋的分割线 =+=+=+=+=+=+=+=+=+=+=+=+==+=+=+=+=+=+=+=+=+=+=+=+=`
`here is the answer： 很多人认为这是简单的Magic Number，其实这背后有内在的原因，这三个数字并不是随便乱选出来的。入门级的选择标准这种伪随机数生成器叫做线性同余生成器（LCG, Linear Congruential Generator)，几乎所有的运行库提供的rand都是采用的LCG，形如：生成的伪随机数序列最大周期m，范围在0到m-1之间。要达到这个最大周期，必须满足`
• c与m互质
• a – 1可以被m的所有质因数整除
• 如果m是4的倍数，a – 1也必须是4的倍数
```

• 是质数 （c = 49297就是质数）
• 接近,(m = 233280时为49297.86460172205)
```

原文作者：艾丽娅的猫
原文地址: https://www.cnblogs.com/yangtze736-2013-3-6/p/3563954.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。

Scroll Up