rand()函数并不能达到真正意义上的产生随机数

作者在 2008-04-11 15:51:28 发布以下内容

 

*/ --------------------------------------------------------------------------------------
*/ 出自: 快乐编程 http://hi.bccn.net/108519
*/ 作者: neverTheSame E-mail:zhaoxufeng9997@126.com QQ:475818502
*/ 时间: 2008-6-1
*/ 声明: 尊重作者劳动,转载请保留本段文字
*/ --------------------------------------------------------------------------------------

rand()函数并不能达到真正意义上的产生随机数.

我的意思是rand()产生的数是有规律可循的:由同一个种子产生的随机数是固定不变的.

在C语言里,设置种子的函数是void  srand (unsigned seed); .请看下面的几个例程:

/*编译环境vc6.0*/

#include<STDIO.H>
#include<STDLIB.H>
int main()
{
 /*设置种子*/
 srand(1000);
 printf("设置种子为1000后,第一次调用rand()的返回值: %d .\n",rand());
 printf("设置种子为1000后,第二次调用rand()的返回值: %d .\n",rand());
 srand(1000);
 if(rand()==3304)
  printf("设置种子后,第n次调用rand()返回的值是确定的.\n");
 else
  printf("设置种子后,第n次调用rand()返回的值是不确定的.\n");
 if(rand()==8221)
  printf("设置种子后,第n次调用rand()返回的值是确定的.\n");
 else
  printf("设置种子后,第n次调用rand()返回的值是不确定的.\n");
 return 0;
}

结果:

设置种子为1000后,第一次调用rand()的返回值: 3304 .
设置种子为1000后,第二次调用rand()的返回值: 8221 .
设置种子后,第n次调用rand()返回的值是确定的.
设置种子后,第n次调用rand()返回的值是确定的.

 

/*编译环境TC2.0*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
 clrscr();
 /*set the seed*/
 srand(1000);
 printf("The return value of calling rand() for the first time : %d ,\n",rand());
 printf("after setting the seed that is 1000 .\n");
 printf("The return value of calling rand() for the second time : %d .\n",rand());
 printf("after setting the seed that is 1000 .\n\n");
 srand(1000);
 if(rand()==18625)
 {
  printf("The return value of calling rand() is confirmed, \n");
  printf("after setting the seed.\n");
 }
 else
 {
  printf("The return value of calling rand() is not confirmed, \n");
  printf("after setting the seed.\n");
 }
 if(rand()==14062)
 {
  printf("The return value of calling rand() is confirmed, \n");
  printf("after setting the seed.\n");
 }
 else
 {
  printf("The return value of calling rand() is not confirmed, \n");
  printf("after setting the seed.\n");
 }
 getch();
 return 0;
}

结果:

The return value of calling rand() for the first time : 18625 ,
after setting the seed that is 1000 .
The return value of calling rand() for the second time : 14062 .
after setting the seed that is 1000 .

The return value of calling rand() is confirmed,
after setting the seed.
The return value of calling rand() is confirmed,
after setting the seed.

从以上二个例程中,可以发现在设置种子之后,每次rand()调用是确定的.

基于以上的原因,C语言提供一个用当前时间来设置随机数生成器的种子randomize().作者建议:在重要的程序设计中,不要使用编译器自动生成的种子.

我的C语言编程经验 | 阅读 3748 次
文章评论,共4条
卧龙孔明
2008-04-12 23:08
1
真正的随机用现在的计算机是无法模拟的,无论是什么函数

如果随即数,我会用
srand((unsigned)time(NULL));
neverTheSame(作者)
2008-04-13 00:24
2
我这一直在想这个问题:试图实现真正的随机数的产生.
srand((unsigned)time(NULL)); 这个方法是一个不错的选择.
neverTheSame(作者)
2008-04-13 00:27
3
卧龙孔明 
你有什么好的方法吗?
可以门交流一下.
neverTheSame(作者)
2008-05-11 21:41
4
基本怎么实现我也不太清楚.
大概是通过一个初始数据(即所谓的种子)开始通过一定的算法而完成的.
如果我在LINUX上看到这个代码,再告诉你吧.
游客请输入验证码