Mersenne twister random numbers not the same as C++
12 ビュー (過去 30 日間)
古いコメントを表示
Hi,
Trying to get the same random numbers in Matlab and C++ by using the Mersenne twister, but Matlab seems to skip every second output of Mersenne twister and also small differences are seen in the 32 bit words that (almost) match the C++ output, see example below.
Is there some way to get the same numbers in Matlab as you get when using the C++ standard?
% Print first 10 numbers from Mersenne twister in interval [0, 2^32-1] with 7 as seed
rng(7, 'twister');
randi([0 4294967295],1,10, 'uint32')'
% Matlab 9.3.0.713579 (R2017b) printout:
% 327741607
% 3349725706
% 1882953311
% 3107259278
% 4200432969
% 2312822152
% 2152296002
% 309457261
% 1152936640
% 2146978992
% C++ implementation and printout
%#include <iostream>
%#include <random>
% using namespace std;
% int main()
% {
% // % Print first 10 numbers from Mersenne twister in interval [0, 2^32-1] with 7 as seed
% std::mt19937 mt_rand(7);
% for (int n = 0; n < 10; n++)
% {
% cout << mt_rand() << endl;
% }
% return 0;
% }
% 327741615
% 976413892
% 3349725721
% 1369975286
% 1882953283
% 4201435347
% 3107259287
% 1956722279
% 4200432988
% 1322904761
0 件のコメント
回答 (1 件)
Shantanu Dixit
2025 年 4 月 24 日
編集済み: Shantanu Dixit
2025 年 4 月 24 日
Hi Tobias, I’ve encountered a similar scenario where the random numbers generated by MATLAB and C++ don’t match. This might be due to MATLAB’s default Mersenne Twister using an implementation that prioritizes full precision floating-point numbers.
As a workaround, I was able to align MATLAB’s output with C++ by configuring the random stream explicitly:
R = RandStream('mt19937ar', 'Seed', 7);
R.FullPrecision = false; % Set to not use full precision
RandStream.setGlobalStream(R); % Set this as the global stream
randi([0 4294967295], 1, 10, 'uint32')'
You can refer to the following documentation to know more about setting the global stream for 'randStream':
'setGlobalStream': https://www.mathworks.com/help/matlab/ref/randstream.randstream.setglobalstream.html
Hope this helps!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Random Number Generation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!