当前位置:网站首页>随机数备注

随机数备注

2022-06-24 06:44:00 雾散睛明

随机数备注
c标准库
stdlib.h
srand:设置随机数种子
rand:参数随机数 范围 0~32767

c++标准库

<random>
default_random_engine

实例:

void testrandom()
{
    
  //该情况不设置随机种子,每次运行时产生的数值一样
  std::default_random_engine random;
  std::cout << random() << std::endl;

  //设置随机种子时,每次运行不会产生相同的数值
  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
  random.seed(seed);
  std::cout << random() << std::endl;
}

minstd_rand 是minstd_rand0的改进版 范围1~2147483646
minstd_rand0 范围1~2147483646
mt19937 范围0~4294967295 40多亿
mt19937_64 64位

minstd_rand0 minstd_rand default_random_engine 都是随机生成器,生成随机数的。

产生指定范围的随机数
uniform_int_distribution 只能是 int、unsigned、short、unsigned short、long、unsigned long、long long、unsigned long long 中的一种
uniform_real_distribution 可选类型为 float、double、long double

分布概率
bernoulli_distribution 是一个分布类,但它不是模板类。它的构造函数只有一个参数,
表示该类返回 true 的概率,该参数默认为 0.5 ,即返回 true 和 false 的概率相等。

以上的用法都是如下的模式

void testrandom2()
{
    
    //返回[0,9]
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine random(seed);

    std::uniform_int_distribution<int> distribution(0,9);
    std::cout << distribution(random) << std::endl;
}

更多详见 <random>

boost库:
示例:

boost::random::mt19937 rng;         // produces randomness out of thin air
                                    // see pseudo-random number generators
boost::random::uniform_int_distribution<> six(1,6);
                                    // distribution that maps to 1..6
                                    // see random number distributions
int x = six(rng);                   // simulate rolling a die
#include <random>
using namespace std;
int main()
{
    
    // 随机数种子
	unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    mt19937 rand_num(seed);	 // 大随机数
	cout << rand_num() << endl;
	return 0;
}

更多详见boost::random库

原网站

版权声明
本文为[雾散睛明]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_25160759/article/details/116212400