1. 程式人生 > >使用c++11生成隨機數

使用c++11生成隨機數

c++的rand()函式只能生成小於3e4的隨機數,很多時候不夠用

使用rand() * rand()實際上也不符合分佈

c++11提供了幾種較好的方法

***,測了下也是1e9

#include <iostream>
#include <random>
using namespace std;

int main()
{
  random_device rd;
  int x = rd();
  cout << x << endl;
  return 0; 
}

mt19937,傳說中的梅森旋轉演算法,測了下最大1e9

#include <iostream>
#include <random>
using namespace std;

int main()
{
  random_device rd;
  mt19937 mt(rd());
  int x = rd();
  cout << x << endl;
  return 0;
}