C:rand,srand (随机数)

rand():

header:stdlib.h

format:int rand ()

parameter:none(通过内部链接的静态变量进行生成pseudo-random integer,即定义在方法之外的static变量)

return:Returns a pseudo-random integer value between ​0​ and RAND_MAX(0 and Rand_MAX included)

function:according to the seed value, get the pseudo-random integer.

How to generate pseudo-random integer: LCG(Linear Congruence Generator)
这里写图片描述

Note:

  1. POSIX requires that the period of the pseudo-random number generator used by rand is at least 2^32(随机数周期至少为2^32)
  2. There are no guarantees as to the quality of the random sequence produced. (especially in randomness)
  3. rand() is not recommended for serious random-number generation needs, like cryptography.(密码学)

srand():

header:stdlib.h
format:void srand(unsigned seed)
function:pseudo-random number generator,used by rand(),as the basic number of random sequence.(为rand中算式中的d)

Note:

  1. If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).(default)
  2. Each time rand() is seeded with the same seed, it must produce the same sequence of values.
  3. Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
  4. Standard practice is to use the result of a call to time(0) as the seed. However, time() returns a time_t value, and time_t is not guaranteed to be an integral type. In practice, though, every major implementation defines time_t to be an integral type, and this is also what POSIX requires.(time(0):获取当前时间,从格林尼治时间开始;然后time(0)的返回值为time_t,因此需要类型转换)

Tips:

  1. 类型转换一定要正确
#include
#include
#include
int main(void){
    srand((long)time(0));
    for(int i=0;i<=10;i++){
        printf("[ 0,%ld],%ld\n",RAND_MAX,rand());
    }
}

在这里,我使用long,应该算是正常的,不过还是有点问题,那就是为什么RAND_MAX为32767,我觉得有点小。不过,如果转换成其他形式(比如long long),RAND_MAX都会发生变化,这一点应该与rand和srand函数内部的数据类型有关,以后再去看一下源代码。

#include
#include
#include
const unsigned long b=1194211693L;
const unsigned long c=12345L;
static unsigned long rand_seed;

void mysrand(unsigned long seed){
    rand_seed=seed;
}

//计算
long myrand(){
    rand_seed=(rand_seed*b+c)%(1<<31-1);
    return rand_seed;
}

double myrandf(){
    return (double)rand_seed/(1<<31-1);
}

int main(void){
    int i;
    mysrand(time(0)); //以时间作为每次程序初始的种子,使每次程序运行的时候产生的随机数不同
    for(i=0;i<50;i++){
        myrand();  //
        printf("  %ld",rand_seed);
        printf("  %lf\n",myrandf());
    }
    return 0;
}

也可以自己编写rand函数和srand函数,不过要注意一些系数的设置。
要令LCG达到最大周期(随机性越强),符合如下条件:

m的所有质因数的积能整除b-1;
若m是4的倍数,b-1也是;
b,c,a0都比m小;
b,c是正整数。Time():返回格林威治时间1970年0时至今的秒数

你可能感兴趣的:(C)