随机函数 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。
实现类似如下 :
官方推荐使用的函数为 :
long int random(void);
返回 0 ------- RAND_MAX 之间的一个 long 类型整数,该函数会产生一个非常大的随机值,最大为 16*((2**31)-1)。
random 函数使用非线性反馈随机数发生器生成默认大小为31个长整数表所返回的连续伪随机数。
void srandom(unsigned int seed);
设置种子值,一般与“当前时间 + 进程ID”作为种子,如果没用调用该函数,则通过random返回的默认种子值为1。
使用方法 :
假如你想产生 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
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
相关文章推荐
- 随机函数 rand,srand,random,srandom 的区别与使用
- 二十四 随机函数 rand,srand,random,srandom 的区别与使用
- 随机函数 rand,srand,random,srandom 的区别与使用
- 随机函数 rand,srand,random,srandom 的区别与使用
- rand,srand,random,srandom
- C++中随机函数rand()和srand()的用法以及time()的使用
- srand()及rand()随机函数使用的两种方法-技术原创。
- rand(),srand(),Randomize(),Random()的区别和用法
- 随机函数rand的使用
- SQL function中使用rand随机函数
- 随机函数SRAND和RAND
- 产生随机数 rand() 和 srand() 函数的使用
- Oracle随机函数包dbms_random使用示例
- 关于产生随机数,使用同一个Random()和不同Random()的区别。
- <stdlib.h>中的随机数产生函数rand,random,srand,srandom的一些知识
- 分享:C++ 随机函数----谈rand() 和 srand() 体会
- C++ 随机函数----谈rand() 和 srand() 体会
- rand()/srand()随机函数
- 随机函数rand的使用
- 随机数 rand()与srand()的区别