Skip to content

Commit f6c3222

Browse files
authored
Add Linear Congruential Generator
1 parent 7dacb2f commit f6c3222

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Misc/LinearCongruentialGenerator.java

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/***
2+
* A pseudorandom number generator.
3+
*
4+
* @author Tobias Carryer
5+
* Date: October 10, 2017
6+
*/
7+
public class LinearCongruentialGenerator {
8+
9+
private double a, c, m, previousValue;
10+
11+
/***
12+
* These parameters are saved and used when nextNumber() is called.
13+
* The current timestamp in milliseconds is used as the seed.
14+
*
15+
* @param multiplier
16+
* @param increment
17+
* @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
18+
*/
19+
public LinearCongruentialGenerator( double multiplier, double increment, double modulo ) {
20+
this(System.currentTimeMillis(), multiplier, increment, modulo);
21+
}
22+
23+
/***
24+
* These parameters are saved and used when nextNumber() is called.
25+
*
26+
* @param seed
27+
* @param multiplier
28+
* @param increment
29+
* @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
30+
*/
31+
public LinearCongruentialGenerator( double seed, double multiplier, double increment, double modulo ) {
32+
this.previousValue = seed;
33+
this.a = multiplier;
34+
this.c = increment;
35+
this.m = modulo;
36+
}
37+
38+
/**
39+
* The smallest number that can be generated is zero.
40+
* The largest number that can be generated is modulo-1. modulo is set in the constructor.
41+
* @return a pseudorandom number.
42+
*/
43+
public double nextNumber() {
44+
previousValue = (a * previousValue + c) % m;
45+
return previousValue;
46+
}
47+
48+
public static void main( String[] args ) {
49+
// Show the LCG in action.
50+
// Decisive proof that the LCG works could be made by adding each number
51+
// generated to a Set while checking for duplicates.
52+
LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
53+
for( int i = 0; i < 512; i++ ) {
54+
System.out.println(lcg.nextNumber());
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)