Monday 15 August 2011

c++ - int multiplication overflow in LCG -


The following is copied from an OpenSource project (RAND), it uses LCG

  rand_next = Rand_next * 1103515245L + 12345L;           

Obviously, Here M2 ^ 32 is

What has happened to me is rand_next * 1103515245L, where I'm pretty sure that will overflow! I take several rand () implementations, all of them in addition to using another C in this way.

Is this overflow harmful? If not, why not?

Thanks

This is fine for unsigned long operations, according to the C99 specification ,:

  A calculation involving unsigned operands can never be higher, as a result the resulting unsigned integer type can not be represented, the modulo number which is larger than the largest value , Which can result in a resultant type.   

So this behavior is not really "overflow", but I call it for simplicity in this reply. For modular arithmetic we have

  a1 â ?? ¡B1 (mod m) a2 ?? ¡B2 (mod m)   

means

  a1 + a2 ?? ¡B1 + b2 (mod m)   

We have

  next * a â? ? ¡° (modern 2 ^ 32)   

where k is with next * a with "overflow" therefore m = 2 ^ 32 ,

  next * a + c â ?? The result with ¡c ++ c (mod M)   

"overflow" is equal to one without "overflow" under modular arithmetic, then the formula is OK. Once we reduce the modules M = 2 ^ 32 , then it will give the same result.

No comments:

Post a Comment