A linear congruential generator is basically an expression which modifies a given value to produce the next value in the series. It takes the form:
xi+1 = (a.xi + b) mod m
as you've already specified (slightly differently: I was taught to always put xi+1 on the left and I still fear my math teachers 25 years later :-), where values for a
, b
and m
are carefully chosen to give a decent range of values. Note that with the mod
operator, you will always end up with a value between 0
and m-1
inclusive.
Note also that the values tend to be integral rather than floating point so if, as you request, you need a value in the range 0-0.999..., you'll need to divide the integral value by m
to get that.
Having explained how it works, here's a simple Java program that implements it using values of a
, b
and m
from your question:
public class myRnd {
// Linear congruential values for x(i+1) = (a * x(i) + b) % m.
final static int a = 25173;
final static int b = 13849;
final static int m = 32768;
// Current value for returning.
int x;
public myRnd() {
// Constructor simply sets value to half of m, equivalent to 0.5.
x = m / 2;
}
double next() {
// Calculate next value in sequence.
x = (a * x + b) % m;
// Return its 0-to-1 value.
return (double)x / m;
}
public static void main(String[] args) {
// Create a new myRnd instance.
myRnd r = new myRnd();
// Output 20 random numbers from it.
for (int i = 0; i < 20; i++) {
System.out.println (r.next());
}
}
}
And here's the output, which looks random to me anyway :-).
0.922637939453125
0.98748779296875
0.452850341796875
0.0242919921875
0.924957275390625
0.37213134765625
0.085052490234375
0.448974609375
0.460479736328125
0.07904052734375
0.109832763671875
0.2427978515625
0.372955322265625
0.82696533203125
0.620941162109375
0.37451171875
0.006134033203125
0.83465576171875
0.212127685546875
0.3128662109375