dimanche 27 septembre 2015

Same random numbers in a for loop

There's a lot of similar question, but I can't find an answer to my problem. I'm writing my own random number generator (for learning purposes). I paste here the important parts of my code:

long rng(long x0, long c, long p)
{
    long x = (c*x0) % p;
    return x;
}

In the main() function, I iterate this rng()

long x2 = 37951;                    // initialize the seed
long c = 69069; long p = pow(2,32); // initialize c and p

for (int i=1; i<=n; i++) {
    long x1 = rng(x2,c,p);
    long x2 = rng(x1,c,p);
    cout << x1 << "\t" << x2 <<endl;
}

As afterwards I want to generate polar coordinates, I need to generate 2 random numbers in each loop. As you can see, the seed is initialized just one time, but the result I become is:

2621237619  504678423
2621237619  504678423
2621237619  504678423
2621237619  504678423
2621237619  504678423

If I only generate x2 (with long x2 = rng(x1,c,p);), I become different results at each loop. Can someone tell me why?




Aucun commentaire:

Enregistrer un commentaire