简体   繁体   中英

random function in C++ and Matlab

I have a code written in Matlab , and I wrote it in C++, but I don't this don't give the same results.

The problem is that I use random function in 3 parts of the code, when I make the random functions fixed , both codes gave the same output.

If any body have any ideas please help me.

The implementation of the rand functions will differ.

You can control the Matlab version through rng .

On the C++ end, I suggest using the functionality in (C++11) <random> (or use Boost's version if your environment is lacking decent C++11 library support) . I can't test right now, but it seems like both sides support the Mersenne Twister. With a bit of luck, the implementation will generate the same numbers if you choose the same seed.

I can't test this now as I don't have Matlab here.

It is because of rand() function give you same numbers. It is better to use srand (time(NULL)); before you call rand() function. srand (time(NULL)); makes rand() to produce different outputs.

For using srand (time(NULL)); function, you should add #include <time.h> or #include <ctime> in your code.

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