C++产生随机数的几种方法小结?

使用cstdlib库

C++11之前,C和C++都用相同的方法来产生随机数(伪随机数),即rand()函数,用法如下:

1)使用srand()撒一个种子

功能:初始化随机数发生器

用法:void srand(unsigned int seed)

2)使用rand()产生随机数

功能:随机数发生器

用法:int rand(void)

3)控制随机数范围

要取得 [a,b) 的随机整数,使用 (rand() % (b-a))+ a;

要取得 [a,b] 的随机整数,使用 (rand() % (b-a+1))+ a;

要取得 (a,b] 的随机整数,使用 (rand() % (b-a))+ a + 1;

** 参考:C++ rand 与 srand 的用法

4)示例代码

#include <iostream>
#include <ctime>
#include <cstdlib>
 
int getRand(int min, int max);
 
int main() {
 
    srand(time(0));
 
    for (int i=0; i<10; i++) {
        int r = getRand(2,20);
        std::cout << r << std::endl;
    }
 
    return 0;
}
 
// 左闭右闭区间
int getRand(int min, int max) {
    return ( rand() % (max - min + 1) ) + min ;
}

使用random库:c++11 random library

C++11之前,无论是C,还是C++都使用相同方式的来生成随机数,而在C++11中提供了随机数库,包括随机数引擎类、随机数分布类,简介如下:

随机数引擎类

一般使用 default_random_engine 类,产生随机非负数(不推荐直接使用)

直接使用时:

#include <iostream>
#include <ctime>
#include <random>
 
int main() {
 
    std::default_random_engine e;
    e.seed(time(0));
 
    for (int i=0; i<10; i++) {
        std::cout << e() << std::endl;
    }
 
    return 0;
}

输出结果:

16807

282475249

1622650073

984943658

1144108930

470211272

101027544

1457850878

1458777923

2007237709

随机数分布类

uniform_int_distribution:产生均匀分布的整数

示例代码:

#include <iostream>
#include <ctime>
#include <random>
 
int main() {
 
    std::default_random_engine e;
    std::uniform_int_distribution<int> u(2,20); // 左闭右闭区间
    e.seed(time(0));
 
    for (int i=0; i<10; i++) {
        std::cout << u(e) << std::endl;
    }
 
    return 0;
}

输出结果:

4

5

16

17

15

17

6

10

13

13

uniform_real_distribution:产生均匀分布的实数

#include <iostream>
#include <ctime>
#include <random>
 
int main() {
 
    std::default_random_engine e;
    std::uniform_real_distribution<double> u(1.5,19.5); // 左闭右闭区间
    e.seed(time(0));
 
    for (int i=0; i<10; i++) {
        std::cout << u(e) << std::endl;
    }
 
    return 0;
}

输出结果:

11.9673

2.29179

9.82668

9.82764

10.2394

13.8324

2.95336

9.72177

16.5145

12.1421

normal_distribution:产生正态分布的实数

示例代码:

#include <iostream>
#include <ctime>
#include <random>
 
int main() {
 
    std::default_random_engine e;
    std::normal_distribution<double> u(0,1); // 均值为0,标准差为1
    e.seed(time(0));
 
    for (int i=0; i<10; i++) {
        std::cout << u(e) << std::endl;
    }
 
    return 0;
}

输出结果:

0.390995

-0.680137

-1.02953

-0.53243

0.375886

-0.19804

-0.796159

0.837714

0.899632

2.06609

bernoulli_distribution:生成二项分布的布尔值

#include <iostream>
#include <ctime>
#include <random>
 
int main() {
 
    std::default_random_engine e;
    std::bernoulli_distribution u(0.8); // 生成1的概率为0.8
    e.seed(time(0));
 
    for (int i=0; i<10; i++) {
        std::cout << u(e) << std::endl;
    }
 
    return 0;
}

输出结果:

1

0

1

1

1

1

1

1

1

1

参考:C++11新特性(75)-随机数库(Random Number Library)

原文地址:https://blog.csdn.net/onion23/article/details/118558454