I am trying to write a Linear congruential generator in python and I find a little piece of code on Wikipedia but have some difficulty on understanding it. The code is as follows:
def lcg(modulus, a, c, seed=None):
if seed != None:
lcg.previous = seed
random_number = (lcg.previous * a + c) % modulus
lcg.previous = random_number
return random_number / modulus
lcg.previous = 2222
My problem is that what is "lcg.previous"? I notice that the function is done, the value of lcg.previous gets updated and stored. Is it declared as a member variable of function lcg() here or actually some kind of default set up for all function in python?
Thanks a lot!
-
Maybe you can give the reference of where you found that code snippet.Alex– Alex2017年04月05日 18:05:23 +00:00Commented Apr 5, 2017 at 18:05
-
I guess you did not copy all the relevant code, and lcg.previous is set to a starting value directly after the function definition.Jan Christoph Terasa– Jan Christoph Terasa2017年04月05日 18:05:42 +00:00Commented Apr 5, 2017 at 18:05
-
Sorry about this, I happen to upload the my edited version. Thanks for editing.Xuan– Xuan2017年04月05日 18:09:26 +00:00Commented Apr 5, 2017 at 18:09
-
1I wonder if this is very old code. A much better way of achieving this would be with generators, but maybe this was written before they were available.Daniel Roseman– Daniel Roseman2017年04月05日 18:14:14 +00:00Commented Apr 5, 2017 at 18:14
-
@DanielRoseman yeah, it is a very old way to generate a uniform random variableXuan– Xuan2017年04月05日 18:16:14 +00:00Commented Apr 5, 2017 at 18:16
3 Answers 3
It is a "member variable" of the function, so that each time it is called (except when called with something for seed) the sequence will pick of where it left off.
2 Comments
static function variables common in other languages, like C.Python is recognizing the lcg.previous as a new variable declaration, and will add it as a member to lcg.
4 Comments
The previous variable is a property on the lcg function. In this example it's being used as a static variable for the lcg function. Since Python doesn't require variables (or object members) to be declared before use you can create them at need. In this case, you've create a member previous of the lcg function object.