0

I'm currently trying to implement the MRG32K3A2 algorithm for random number generation in C++. I proto-typed my program in R prior to implementing in C++, and now i'm noticing some wierd behaviour with my C++ program.

The problem boils down to the following computation:

long long m2 = 4294944443;
long long a21 = 527612;
long long a23 = -1370589;
int seed = 12345;
long long test1 = a21*seed+a23*seed
long long test2 = test1 % m2 // Modulo here

Doing this computation in for instance R or Excel gives

test1 = -10406551065
test2 = 2478282264

Doing it in C++ gives me

test1 = -10406551065
test2 = -1816662179

I'm sure there's a good reason for this, but i just don't get it. I'm programming in Visual C++ (2015) if that makes a difference.

Thanks in advance

amri
  • 77
  • 8
  • They're the same answer - in a strange way. c++ has returned a -ve value because your input was negative, but if you do m2 - test2(R) you'll see it gives you test2(C++) โ€“ UKMonkey Oct 27 '16 at 16:35
  • C and C++ both define the return value of `a % b` to be negative when only one of `a` and `b` are negative. C11 (ISO/IEC 9899:2011 ยง6.5.5 **Multiplicative operators**) says: _When integers are divided, the result of the `/` operator is the algebraic quotient with any fractional part discarded. If the quotient `a/b` is representable, the expression `(a/b)*b + a%b` shall equal `a`; otherwise, the behavior of both `a/b` and `a%b` is undefined._ โ€“ Jonathan Leffler Oct 27 '16 at 16:36
  • `long long` makes no difference in this case. โ€“ Mark Ransom Oct 27 '16 at 16:39

0 Answers0