Skip to content

Instantly share code, notes, and snippets.

@adpoe
Created March 23, 2016 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adpoe/39b039cb6770cf4bb16c to your computer and use it in GitHub Desktop.
Save adpoe/39b039cb6770cf4bb16c to your computer and use it in GitHub Desktop.
LCG Example
def generate_lcg( num_iterations ):
"""
LCG - generates as many random numbers as requested by user, using a Linear Congruential Generator
LCG uses the formula: X_(i+1) = (aX_i + c) mod m
:param num_iterations: int - the number of random numbers requested
:return: void
"""
# Initialize variables
x_value = 123456789.0 # Our seed, or X_0 = 123456789
a = 101427 # Our "a" base value
c = 321 # Our "c" base value
m = (2 ** 16) # Our "m" base value
# counter for how many iterations we've run
counter = 0
# Open a file for output
outFile = open("lgc_output.txt", "wb")
#Perfom number of iterations requested by user
while counter < num_iterations:
# Store value of each iteration
x_value = (a * x_value + c) % m
#Obtain each number in U[0,1) by diving X_i by m
writeValue = str(x_value/m)
# write to output file
outFile.write(writeValue + "\n")
# print "num: " + " " + str(counter) +":: " + str(x_value)
counter = counter+1
outFile.close()
print("Successfully stored " + str(num_iterations) + " random numbers in file named: 'lgc_output.txt'.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment