For example here: http://www.math.cornell.edu/~mec/Winter2009/Luo/Linear%20Congruential%20Generator/linear%20congruential%20gen1.html
I am trying to implement an LCG for an example problem set, but it's not working for me and I cant seem to figure out why?
The equation is straight forward: Xn+1 =(aXn + c) mod m
From the reference above: For example, the sequence obtained when X0 = a = c = 7, m = 10, is 7, 6, 9, 0, 7, 6, 9, 0, ...
Implementing this in java, for example -
public static void lcg(){
int a = 7;
int c = 7;
int m = 10;
int x0 = 7;
int N = 10;
for (int x = x0; x < x0+N; x++){
int result = (a*x + c) % m;
System.out.println(result);
}
I get the output: 6 3 0 7 4 1 8 5 2 9
Rather than the expected 7,6,9,0,...
I get the same on paper. Can anyone figure out what is going wrong?
Similarly, a=10, c=7, m=11, x0 = 3 should give a repeating pattern of 4,3,4,3 but I get 4 3 2 1 0 10 9 8 7 6
This seems to just be a misunderstanding of iteration. It doesn't appear to be a problem with the equation, but what you do with the result of the equation.
I read Xn+1 = (aXn + c) mod m
as
The next value of x will be the current value of
x
, plusc
, modm
".
Note my emphasis. You're throwing away the current value of x
(result
), then just using the "iteration counter variable" in the equation in the next iteration.
Change the loop to
for (int x = x0, i = 0; i < 5; i++) {
// Note x is being updated instead
x = (a*x + c) % m;
System.out.print(x);
}
69076