Lee
Lee

Reputation: 13

How to generate not repeated random variables by Mersenne Twister

I want to generate 1000 different values of k and calculate the mean and variance of k, but when I use MT, it is always the same number in the spreadsheet. Following is my code and hope someone can help me. Thank you very much!

int main(int argc, char * const argv[]) {

int simNum=1000;
double x=1;
int k=0;
ofstream fout("hw2(part 2-b).csv");
int seed=time(0);
MTRand_open mt(seed);



for(int i=0;i<simNum;i++)
{


    while(x>=exp(-3))
    {

        x*=mt();

        k++;
    }


    fout<<i<<","<<x<<","<<k-1<<endl;

}

system("Pause");
return 0;

}

Upvotes: 0

Views: 89

Answers (1)

Michael Burr
Michael Burr

Reputation: 340188

You need to reset x in your loop - right now, once the condition of x >= exp(-3) becomes false the code will never call the mt() function to get another random number.

for(int i=0;i<simNum;i++)
{


    while(x>=exp(-3))
    {

        x*=mt();

        k++;
    }


    fout<<i<<","<<x<<","<<k-1<<endl;

    x = 1; // <-- reset x

}

Upvotes: 2

Related Questions