简体   繁体   中英

Matlab rand and c++ rand()

I am trying to port a matlab code into c++ and found the usage of rand in matlab . Is matlab's rand function and c++ rand() function same? If not, is there any inbuilt function for matlab's rand in C++ or opencv?

Given that the C++ Standard only loosely defines rand() , you can not assert that it is equivalent to the matlab function.

Fortunately, C++11 now has a suite of generators which are standardised in the standard include header <random> . For example, std::mt19937 is a Mersenne twister generator and std::minstd_rand is a linear congruential generator which allows you to configure the sequence coefficients.

My guess is that the Matlab generator can be replicated with this latter one. Refer to the Matlab docs for the specific details. Fortunately, testing your code will be trivial.

Bathsheba's guess is almost correct: Matlab R2017A uses the MT19937 algorithm, not a LC algorithm as its default random number generator; the source for rand.m actually includes the copyright notice from the 2002 version of Nishimura and Matsumoto's MT19937 C Program .

In C++ 11, the default seed is set to 5489, which is identical to Matlab's default seed, (and to the default seed in the referenced C program).

So, the following Matlab code:

rng('default');
a = rand();
a = rand();
a = rand();

will output identical values to the C++ code:

std::mt19937 rng;
std::uniform_real_distribution<float> urd(0, 1);
a = urd(rng);
/* skip alternate values */ rng();
a = urd(rng);
/* skip alternate values */ rng();
a = urd(rng);

Note: To replicate Matlab's output , use std::uniform_real_distribution<float> not std::uniform_real_distribution<double> .

EDIT : Matlab appears to skip every other value after each call to rand() , by comparison with C++. I've compared Matlab output with that of both MSVC 2017 and GCC 5.4; both of the latter behave identically to each other. As there are no guarantees regarding the individual values produced by rand() , this "non-standard" behavior obviously can't be classed as a bug. The code samples above take this behavior into account.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM