generators : random shootout

GerritM gmuller at worldonline.nl
Wed Jan 16 13:00:02 EST 2002


"Mark McEahern" <marklists at mceahern.com> schreef in bericht
news:mailman.1011133703.32121.python-list at python.org...
> GerritM wrote:
> > can this instead be replaced by:
> >
> > for i in gen_random(100.0): pass
>
> Short answer:  No.
>
<...snip...>
Directly after logging off I realized the reasoning myself, how stupid. The
problem is that reading
http://www.amk.ca/python/2.2/index.html the generator example with integers
the N is used as number, instead of a seed as here. The reason for still
thinking/searching for alternatives is that the current solution is longer
(in lines of code) as well as slower. Because the generator solution seems
an elegant solution, I would like an overall solution which is objective
better.

> Below is the solution I ended up with, in case you'd like to tinker with
it.
> As the shootout site stated, the solution should generate 8.163294467 for
N
> = 1000.
>
> Cheers,
>
> // mark
>
> #! /usr/bin/env python
> # gen2.py
> # based on: http://www.bagley.org/~doug/shootout/
>
> 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():
>     try:
>         N = int(sys.argv[1])
>     except IndexError:
>         N = 1000
>     if N < 1:
>         N = 1
>     gr = gen_random(100.0)
>     for i in xrange(1, N):
>         gr.next()
>     print "%.9f" % gr.next()
>
> import time
> timeIn = time.time()
> main()
> timeOut = time.time()
>
> print "%f seconds." % (timeOut - timeIn)
>
regards Gerrit

--
www.extra.research.philips.com/natlab/sysarch






More information about the Python-list mailing list