c - using srand and rand, I am getting same number after few iteration -
i having problem of getting same number generation problem using rand , srand functions.
srand ((unsigned int) time (null)); unsigned int m_random1 = 96047236; unsigned int m_random2 = 7955217; unsigned int m_random3 = (1 + (int) (23445234.0 * rand()/(rand_max+1.0))); // code provides me random number.`enter code here` (unsigned int i= 0; i<20;i++) { m_random3 = m_random1 * m_random3 + m_random2; printf("m_random3 = %x, count = %d",m_random3, i); printf ("\n"); } i getting same result (b2673e25) after iteration:
m_random3 = a832cbbd, count = 0 m_random3 = 39d9c085, count = 1 ..... ..... m_random3 = 4a673e25, count = 12 m_random3 = 12673e25, count = 13 m_random3 = 32673e25, count = 14 m_random3 = b2673e25, count = 15 m_random3 = b2673e25, count = 16 m_random3 = b2673e25, count = 17 m_random3 = b2673e25, count = 18 m_random3 = b2673e25, count = 19 any body has idea why happening ??
this has nothing rand(). have implemented linear congruential generator (lcg) unsuitable constants. such generator calculates next number current value:
x[i + 1] = (a*x[i] + c) % m; in example, (inappropraiely named) random1 a, random2 c , m implicitly uint_max, because of modular behaviour of unsigned ints.
the wikipedia page doesn't provide method determine cycle length, has conditions largest cycle length, m:
c,mrelatively prime: that's true, prime factors area == 2 * 2 * 53 * 453053 c == 9 * 23 * 38431a - 1divisible prime factors ofm:mpower of two,aeven.a - 1odd , not divisible 2.a - 1multiple of 4 ifmmultiple of 4: that's not true either.
you try using of constants given in wikipedia article. or use rand().
Comments
Post a Comment