Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathLinearCongruentialGenerator.java
More file actions
Latest commit
68 lines (62 loc) · 2.04 KB
/
Copy pathLinearCongruentialGenerator.java
File metadata and controls
68 lines (62 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
packagecom.thealgorithms.others;
/**
* *
* A pseudorandom number generator.
*
* @author Tobias Carryer
* @date October 10, 2017
*/
publicclassLinearCongruentialGenerator {
privatefinaldoublea;
privatefinaldoublec;
privatefinaldoublem;
privatedoublepreviousValue;
/**
* *
* These parameters are saved and used when nextNumber() is called. The
* current timestamp in milliseconds is used as the seed.
*
* @param multiplier
* @param increment
* @param modulo The maximum number that can be generated (exclusive). A
* common value is 2^32.
*/
publicLinearCongruentialGenerator(doublemultiplier, doubleincrement, doublemodulo) {
this(System.currentTimeMillis(), multiplier, increment, modulo);
}
/**
* *
* These parameters are saved and used when nextNumber() is called.
*
* @param seed
* @param multiplier
* @param increment
* @param modulo The maximum number that can be generated (exclusive). A
* common value is 2^32.
*/
publicLinearCongruentialGenerator(doubleseed, doublemultiplier, doubleincrement, doublemodulo) {
this.previousValue = seed;
this.a = multiplier;
this.c = increment;
this.m = modulo;
}
/**
* The smallest number that can be generated is zero. The largest number
* that can be generated is modulo-1. modulo is set in the constructor.
*
* @return a pseudorandom number.
*/
publicdoublenextNumber() {
previousValue = (a * previousValue + c) % m;
returnpreviousValue;
}
publicstaticvoidmain(String[] args) {
// Show the LCG in action.
// Decisive proof that the LCG works could be made by adding each number
// generated to a Set while checking for duplicates.
LinearCongruentialGeneratorlcg = newLinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
for (inti = 0; i < 512; i++) {
System.out.println(lcg.nextNumber());
}
}
}