Skip to content

Commit 875c6cd

Browse files
authored
Add Linear Congruential Generator
1 parent f9156cf commit 875c6cd

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Diff for: other/LinearCongruentialGenerator.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
__author__ = "Tobias Carryer"
2+
3+
from time import time
4+
5+
class LinearCongruentialGenerator(object):
6+
"""
7+
A pseudorandom number generator.
8+
"""
9+
10+
def __init__( self, multiplier, increment, modulo, seed=int(time()) ):
11+
"""
12+
These parameters are saved and used when nextNumber() is called.
13+
14+
modulo is the largest number that can be generated (exclusive). The most
15+
efficent values are powers of 2. 2^32 is a common value.
16+
"""
17+
self.multiplier = multiplier
18+
self.increment = increment
19+
self.modulo = modulo
20+
self.seed = seed
21+
22+
def next_number( self ):
23+
"""
24+
The smallest number that can be generated is zero.
25+
The largest number that can be generated is modulo-1. modulo is set in the constructor.
26+
"""
27+
self.seed = (self.multiplier * self.seed + self.increment) % self.modulo
28+
return self.seed
29+
30+
if __name__ == "__main__":
31+
# Show the LCG in action.
32+
lcg = LinearCongruentialGenerator(1664525, 1013904223, 2<<31)
33+
while True :
34+
print lcg.next_number()

0 commit comments

Comments
 (0)