您的位置:首页 > 其它

随机函数 rand,srand,random,srandom 的区别与使用

2014-11-05 14:28 417 查看
函数定义:

int rand(void); 返回 0 ------- RAND_MAX 之间的一个 int 类型整数,该函数为非线程安全函数。并且生成随机数的性能不是很好,已经不推荐使用。

void srand(unsigned int seed); 设置种子值,一般与“当前时间 + 进程ID”作为种子,如果没用调用该函数,则通过rand返回的默认种子值为1。

实现类似如下 :
static unsigned long next = 1;

void my_srand(unsigned seed) {
next = seed;
}

/* RAND_MAX assumed to be 32767 */
int my_rand(void) {
next = next * 1103515245 + 12345;
return((unsigned)(next/65536) % 32768);
}


官方推荐使用的函数为 :

long int random(void);

返回 0 ------- RAND_MAX 之间的一个 long 类型整数,该函数会产生一个非常大的随机值,最大为 16*((2**31)-1)。

random 函数使用非线性反馈随机数发生器生成默认大小为31个长整数表所返回的连续伪随机数。

void srandom(unsigned int seed);

设置种子值,一般与“当前时间 + 进程ID”作为种子,如果没用调用该函数,则通过random返回的默认种子值为1。

#include<stdlib.h>
#include<stdio.h>
#include<time.h>
int main()
{
srandom( time( NULL ) );
int i;
for ( i = 0; i < 10; i++ )
{
printf( "%ld ", random() % 10 );
}
printf( "\n" );
return 0;
}


使用方法 :

假如你想产生 1 ------10 之间的一个随机数, 你应该像下面这样编码

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
而不是下面这样的代码

j = 1 + (rand() % 10);

结论:



如果你使用 srandom 种植种子, 则你应该使用 random 返回随机数, 如果你使用 srand 种植种子, 则你应该使用rand返回随机数。

不过srand和rand官方已经不推荐使用。原因是产生随机数的性能不是很好, 另外是随机数的随机性没有random好, 再者就是不是线程安全。

/article/7663364.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: