如何让升压::随机和Matlab产生相同随机数 [英] How to let Boost::random and Matlab produce the same random numbers

查看:192
本文介绍了如何让升压::随机和Matlab产生相同随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要检查我的C ++ code,我希望能够让升压::随机和Matlab产生相同随机数。

To check my C++ code, I would like to be able to let Boost::Random and Matlab produce the same random numbers.

因此​​,对于升压我用code:

So for Boost I use the code:

boost::mt19937 var(static_cast<unsigned> (std::time(0)));
boost::uniform_int<> dist(1, 6);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(var, dist);
die.engine().seed(0);     
for(int i = 0; i < 10; ++i) {
    std::cout << die() << " ";
}      
std::cout    << std::endl;

将会产生(程序的每次运行):结果
4 4 5 6 4 6 4 6 3 4

而对于MATLAB我使用:

And for matlab I use:

RandStream.setDefaultStream(RandStream('mt19937ar','seed',0));
randi(6,1,10)

将会产生(程序的每次运行):结果
5 6 1 6 4 1 2 4 6 6

这是奇怪的,因为都使用相同的算法,相同的种子。
我怎么错过?

Which is bizarre, since both use the same algorithm, and same seed. What do I miss?

看来,Python的(使用numpy的)和Matlab似乎不相上下,在随机统一编号:
Matlab的

It seems that Python (using numpy) and Matlab seems comparable, in the random uniform numbers: Matlab

RandStream.setDefaultStream(RandStream('mt19937ar','种子',203));兰特(1,10)

RandStream.setDefaultStream(RandStream('mt19937ar','seed',203));rand(1,10)

0.8479 0.1889 0.4506 0.6253 0.9697 0.2078 0.5944 0.9115 0.2457 0.7743

的Python:
random.seed(203); random.random(10)

Python: random.seed(203);random.random(10)

阵列([0.84790006,0.18893843,0.45060688,0.62534723,0.96974765,
        0.20780668,0.59444858,0.91145688,0.24568615,0.77430378])

C ++升压

0.8479 0.667228 0.188938 0.715892 0.450607 0.0790326 0.625347 0.972369 0.969748 0.858771

这是等同于以往其他Python和Matlab值...

Which is identical to ever other Python and Matlab value...

推荐答案

我有其他的答案同意,指出这些发电机都没有绝对。它们可以根据实现产生不同的结果。我认为,最简单的解决办法是实现自己的发电机。它看起来令人生畏(梅森倍捻机是肯定的方式),但看看 Xorshift ,一个极其简单但强大的一个。我复制维基百科的链接中给出的C实现:

I have to agree with the other answers, stating that these generators are not "absolute". They may produce different results according to the implementation. I think the simplest solution would be to implement your own generator. It might look daunting (Mersenne twister sure is by the way) but take a look at Xorshift, an extremely simple though powerful one. I copy the C implementation given in the Wikipedia link :

uint32_t xor128(void) {
  static uint32_t x = 123456789;
  static uint32_t y = 362436069;
  static uint32_t z = 521288629;
  static uint32_t w = 88675123;
  uint32_t t;

  t = x ^ (x << 11);
  x = y; y = z; z = w;
  return w = w ^ (w >> 19) ^ (t ^ (t >> 8));
}

要具有相同的种子,只要把你想INT X,Y,Z的任何值,W(除(0,0,0,0)我相信)。你只需要确保Matlab与C ++同时使用32位对于这些unsigned int类型。

To have the same seed, just put any values you want int x,y,z,w (except(0,0,0,0) I believe). You just need to be sure that Matlab and C++ use both 32 bit for these unsigned int.

这篇关于如何让升压::随机和Matlab产生相同随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆