generators : random shootout
Mark McEahern
marklists at mceahern.com
Fri Jan 11 13:57:53 EST 2002
In trying to understand generators, I modified the Python code in the random
number generator shootout to use generators.
The shootout:
http://www.bagley.org/~doug/shootout/bench/random/
The existing Python implementation:
http://www.bagley.org/~doug/shootout/bench/random/random.python
Python random number generator (using generators) is at the bottom of this
post.
Doing some simple timing tests, it appears that the "old" method runs
slightly faster. Is that expected?
Thanks,
// mark
#! /usr/bin/env python
from __future__ import generators
import sys
IM = 139968 # modulo
IA = 3877 # multiplier
IC = 29573 # increment
def gen_random(max):
last = 42 # initialize
while 1: # this generator can be called
indefinitely
last = (last * IA + IC) % IM # update prior value
rand = max * last / IM # generate the random number
yield rand # yield it
def main():
N = int(sys.argv[1])
if N < 1:
N = 1
gr = gen_random(100.0)
for i in xrange(1, N):
gr.next()
print "%.9f" % gr.next()
main()
More information about the Python-list
mailing list