首页 > 编程语言 > 详细

随机函数rand()算法

时间:2014-11-30 06:39:00      阅读:238      评论:0      收藏:0      [点我收藏+]

今天学习了一下随机函数rand的算法。

这个算法叫做线性同余算法(linear congruential generator (LCG))。

不同的编译器取的常数不同,可以参考wiki:http://en.wikipedia.org/wiki/Linear_congruential_generator

以下程序可以输出和系统一样的随机数。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 
 5 #define _A 214013LL
 6 #define _B 2531011LL
 7 
 8 
 9 int a;
10 
11 
12 void mysrand(int x)
13 {
14     a = x;
15 }
16 
17 
18 int myrand()
19 {
20     return ((a = a * _A + _B)>>16) & 0x7fff;
21 }
22 
23 
24 int main()
25 {
26     mysrand(0);
27     srand(0);
28     while (1)
29     {
30         printf ("%d, %d\n", rand(), myrand());
31         getchar();
32     }
33     return 0;
34 }

 

随机函数rand()算法

原文:http://www.cnblogs.com/lzsz1212/p/4132594.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!