C/C++ (伪)随机数

1. C 随机数

  • 包含头文件

  • 生成随机数

    int rand(void);
    

    返回一个0RAND_MAX 范围内的伪随机整数。通常使用 取余操作(%) 实现生成指定范围内的随机数。
    该函数使用的算法使用种子生成序列,应使用 srand 函数将其初始化为某个独特的值。

  • 初始化随机数生成器

    void srand(unsigned int seed);
    

    使用种子 seed 初始化伪随机数生成器。

    如果使用不同的种子,则将生成不同的随机数序列。

    如果使用相同的种子初始化两个不同的随机数生成器,则它们将在随后的 rand 调用中生成相同的连续结果。

    如果seed设置为1,则将生成器重新初始化为其初始值,并生成与调用randsrand之前相同的值。

    srand 通常被初始化为一些独特的运行时值,比如 time 函数返回的值(在头文件 中声明), 这足以满足大多的随机需求。

  • 例子1

    /* srand example */
    #include       /* printf, NULL */
    #include      /* srand, rand */
    #include        /* time */
    
    int main () {
    	  printf ("First number: %d\n", rand()%100);
    	  
    	  srand (time(NULL));
    	  printf ("Random number: %d\n", rand()%100);
    	  
    	  srand (1);		// 重新初始化为 srand 调用之前的种子值
    	  printf ("Again the first number: %d\n", rand()%100);
    	
    	  return 0;
    }
    

    结果:
    First number: 41
    Random number: 13
    Again the first number: 41

  • 例子2:

    /* rand example: guess the number */
    #include       /* printf, scanf, puts, NULL */
    #include      /* srand, rand */
    #include        /* time */
    
    int main () {
    	  int iSecret, iGuess;
    	
    	  /* initialize random seed: */
    	  srand (time(NULL));
    	
    	  /* generate secret number between 1 and 10: */
    	  iSecret = rand() % 10 + 1;
    	
    	  do {
    		    printf ("Guess the number (1 to 10): ");
    		    scanf ("%d",&iGuess);
    		    if (iSecret<iGuess) puts ("The secret number is lower");
    		    else if (iSecret>iGuess) puts ("The secret number is higher");
    	  } while (iSecret!=iGuess);
    	
    	  puts ("Congratulations!");
    	  return 0;
    }
    

2. C++ 随机数

  • 包含头文件 ,包括随机数引擎类随机数分布类

  • 引擎类可以生成 unsigned 随机数序列;分布类使用引擎类生成指定类型、在给定范围内的、服从特定概率分布的随机数。

  • 随机数引擎
    随机数引擎是函数对象类,它们定义了一个调用运算符,该运算符不接受参数,并返回一个随机的 unsigned 整数。

    default_random_engine e;		// 随机数引擎
    for(int i=0; i<10; i++) {
        cout << e() << " ";
    }
    

    引擎的操作 :标准库中定义了多个随机数引擎类,下面用Engine表示

    函数声明 解释
    Engine e; 默认构造函数,使用默认的种子
    Engine e(s); 使用整数 s 作为种子构造引擎
    e.seed(s); 使用整数 s 作为种子重置引擎的状态
    e.min();
    e.max();
    此引擎可生成的最小值和最大值
    e.discard(u); 将引擎推进u步
  1. 如果两个引擎使用相同的种子,则它们将生成相同的值序列
  2. 使用指定的种子可以每次都生成相同的序列。
  3. 使用 time 作为种子:
    default_random_engine e(time(0));	// time(0)以秒为单位返回当前时间
    

  • 随机数分布
    随机数分布类也是函数对象类,定义了一个调用运算符,它接受一个随机数引擎作为参数,分布对象使用它的引擎参数生成随机数,并将其映射到指定的分布。如,

    // 随机数分布类:生成  0到 9 之间(包含首尾)均匀分布的随机数
    uniform_int_distribution<unsigned> u(0, 9);
    default_random_engine e;
    
    for(int i=0; i<10; i++) {
        cout << u(e) << " ";
    }
    
    uniform_real_distribution<double> u(0, 1);		// 生成0到1之间的均匀分布
    // 还有其他分布...
    

你可能感兴趣的:(C++)