老婆大人有点暖夏哲霆:获得随机函数的算法原理常用有哪几种?

来源:百度文库 编辑:神马品牌网 时间:2024/05/11 05:00:59
简述原理.不要程序代码.

我所知道的是用移位的办法做到的,被移位的数称为种子。

前两天发现rand()函数并不随机,找到这篇文章,这是比较简单的算法
/*1.从同一个种子开始*/
#include <stdio.h>
#include <conio.h>
static unsigned long int next=1;

int rand0(void)
{
next=next*1103515245+12345;
return (unsigned int)(next/65536)%32768;
}

int main(void)
{
int count;

for(count=0;count<5;count++)
printf("%hd\n",rand0());
getch();
return 0;
}

/*2.重置种子*/
#include <stdio.h>
#include <conio.h>
static unsigned long int next=1;

int rand1(void)
{
next=next*1103515245+12345;
return (unsigned int)(next/65536)%32768;
}

void srand1(unsigned int seed)
{
next=seed;
}

int main(void)
{
int count;
unsigned int seed;

printf("please input seed:");
scanf("%u",&seed);
srand1(seed);
for(count=0;count<5;count++)
printf("%hd\n",rand1());
getch();
return 0;
}

/*3.利用利用时钟产生种子
ANSI C程序库提供了rand()函数来产生随机数;
ANSI C程序库提供了srand()函数来产生种子;
ANSI C程序库提供了time()函数返回系统时间。
*/
#include <time.h>
#include <stdio.h>
#include <dos.h>
#include <conio.h>
#include <stdlib.h>

int main(void)

{
int i;
time_t t;
clrscr();
t = time(NULL);
srand((unsigned) t);
for(i=0; i<10; i++) printf("%d\n", rand()%10);
getch();
return 0;
}