Reputation: 13
I was using the following code to generate two 2D random arrays:
#include <iostream>
#include <string>
#include <random>
#include <iomanip>
#include <new>
#include <math.h>
int main ()
{
std::default_random_engine generator,generator2;
std::normal_distribution<double> distribution;
double **peta, **pxi;
const int Nmodes =200;
const double PI=3.1415926;
peta = new double*[3];
pxi = new double*[3];
for (int i=0; i<3; ++i)
{
peta[i] = new double[Nmodes];
pxi[i] = new double[Nmodes];
}
distribution.param(std::normal_distribution<double>(0.0,1.0).param());
for (int i=0; i<3; ++i)
{
for (int j=0; j<Nmodes; ++j)
{
peta[i][j]=distribution(generator);
// pxi[i][j] =distribution(generator2); //1st case
}
for (int j=0; j<Nmodes; ++j)
{
pxi[i][j] =distribution(generator2); //2nd case
}
}
std::cout<<std::setprecision(15)<<"peta "<<peta[0][20]<<'+'<<peta[1][20]<<'+'<<peta[2][20]<<'+'<<peta[2][30]<<std::endl;
std::cout<<"pxi "<<pxi[0][20]<<"+"<<pxi[1][20]<<'+'<<pxi[2][20]<<'+'<<pxi[2][30]<<std::endl;
for (int i=0; i<3; ++i)
{
delete [] peta[i];
delete [] pxi[i];
}
delete [] peta;
delete [] pxi;
return 0;
}
In above code,I generated peta and pxi 2d arrays. In the first case I wrote them together in the nested for loops while in the second case I wrote them separately for the second loop (please see the comment region in the code). For the case 1, peta and pxi are different but they the are the same in case 2. I think they should be the same because the generators are equivalent even they are different variables. I used gcc 4.8.4 with -std=c++11 option to compile. Does anyone know the reason? I appreciate your help.
Upvotes: 1
Views: 42
Reputation: 52611
A typical implementation of std::normal_distribution
implements Box–Muller transform - an algorithm that produces normally distributed numbers in pairs. So the first time you call it, it produces a pair of numbers and returns the first one, saving the second one for later. The second time you call it, it returns that saved number. The third time you call it, it again produces two numbers; lather, rinse repeat.
Thus, your first case never actually uses generator2
. distribution(generator)
call manufactures two numbers - one goes into peta
, the other into pxi
.
In the second case, peta
is populated from generator
and pxi
from generator2
. You don't seed either of them, which means they both start with the same seed (whatever the default is), and both produce the same random sequence. So you end up with the same values in both arrays.
Upvotes: 1