随机数¶
注:计算机没有真正的随机
1 c随机数¶
c随机数需要先分配一个随机数种子给srand
,随机数生成完全取决于这个种子,如果这个种子相同,每次启动程序,随机的结果都会一样,通常我们使用时间数据来作为这个种子。
步骤如下:
1. void srand(unsigned int __seed)
初始随机数种子
2. int rand()
获取随机数
#include <cstdlib>
#include <ctime>
#include <stdio.h>
int main()
{
using namespace std;
srand(time(NULL));
for (size_t i = 0; i < 10; i++)
{
printf("随机数1:%d\n", rand());
}
}
2 c++随机数¶
c++标准库提供引擎和分布来满足大部分随机数的需求
- 头文件random
- 步骤:
1. 创建引擎
2. 设置随机数种子
3. 创建分布
4. 生成随机数
与 c 随机数比较:步骤 1 和 2 对应 c 随机数的步骤 1,步骤 3 可以没有,但建议采用,步骤 4 对应 c 随机数的步骤 2。 - 示例代码
#include<random>
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
//1.创建引擎
default_random_engine eg;
//2.设置随机数种子
eg.seed(time(NULL));
//3.选择分布
uniform_int_distribution<int> di(10, 20);
//4.生成随机数
std::cout << "uniform_int_distribution随机数" << endl;
for (size_t i = 0; i < 10; ++i)
{
std::cout << "随机数" << i << "=" << di(eg) << endl;
}
std::cout << "******************" << endl;
std::cout << "default_random_engine随机数" << endl;
for (size_t i = 0; i < 10; ++i)
{
std::cout << "随机数" << i << "=" << eg() << endl;
}
std::cout << "******************" << endl;
}
- 可能结果
uniform_int_distribution随机数
随机数0=14
随机数1=20
随机数2=12
随机数3=16
随机数4=17
随机数5=17
随机数6=13
随机数7=20
随机数8=17
随机数9=13
******************
default_random_engine随机数
随机数0=3159708447
随机数1=2335960522
随机数2=2934329899
随机数3=3967235533
随机数4=208943683
随机数5=96685374
随机数6=2652946313
随机数7=1264354277
随机数8=628896870
随机数9=1091072451
******************
2.1 引擎¶
- 引擎是随机数的源头,是function object(函数对象),能够产生随机的无正负值,并均匀的分布在预定义的最小最大值之间
- 引擎可设置种子来使产生不同的随机数
- 引擎有多种,如
default_random_engine
linear_congruential_engine
mersenne_twister_engine
subtract_with_carry_engine
2.2 分布¶
- 将引擎产生的随机值转换为符合给定的分布在某一区间的随机数。
- 分布有很多,如
uniform_int_distribution
3 参考资料¶
c++随机数涉及了许多不同实现的引擎和分布,详细资料请参考cppreference