mt19937

背景

  • 你需要把原来mtalab的代码翻译为c、python等等
  • 你的代码里使用了随机数
  • 你的老板又要求你实现的方法exactly the same
  • 参考这里

mt19927

  • Mersenne Twister是目前比较常用的随机数生成器
  • 周期非常长$2^{19937}-1$,速度非常快

python代码

1
2
3
4
5
6
7
import numpy as np
np.random.seed(1337)
A = np.random.random((5,3))
A.T
array([[ 0.26202468, 0.45931689, 0.26194293, 0.11527423, 0.12505793],
[ 0.15868397, 0.32100054, 0.97608528, 0.38627507, 0.98354861],
[ 0.27812652, 0.51839282, 0.73281455, 0.62850118, 0.44322487]])

MATLAB代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
rand('twister', 1337);
A = rand(3,5)
A =
Columns 1 through 2
0.262024675015582 0.459316887214567
0.158683972154466 0.321000540520167
0.278126519494360 0.518392820597537
Columns 3 through 4
0.261942925565145 0.115274226683149
0.976085284877434 0.386275068634359
0.732814552690482 0.628501179539712
Column 5
0.125057926335599
0.983548605143641
0.443224868645128

c++代码

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <random>

int main()
{
unsigned seed1 = 1337;
std::mt19937 g1(seed1);
for(int i=0; i<100; i++)
std::cout << 1.0*g1()/g1.max() << std::endl;
}

还有一些

最简单的生成算法,混合同余法,可以看这里

c++11的random库,可以参考这里