FAQ
To keep a simulation tidy, I created a dispatcher that generates
random variables drawn from various distributions as follows:

import random

RVType = 1 #Type of random variable - pulled from RVDict

RVDict= {'1': random.betavariate(1,1), '2': random.expovariate(1),
'3': random.gammavariate(1,1), '4': random.gauss(0,1),
'5': random.lognormvariate(1,1), '6':
random.paretovariate(1),
'7': random.uniform( -1,1), '8':
random.weibullvariate(1,2) }

x = []
y=[]

rv = RVDict[str(RVType)]
for i in range(N):
x.append(rv)
y.append(rv)


Oddly, x and y get filled with a single value repeated N times. I
expected to get a different random number appear each time I called
rv ,but this does not happen. Instead, my first call to rv generates a
random number from the appropriate distribution, while subsequent
calls simply repeat the random number generated in the first call.
Where am I going wrong?

Thanks in advance for your help.

Sincerely


Thomas Philips

Search Discussions

  • George Sakkis at Mar 30, 2008 at 10:20 pm

    On Mar 30, 5:06 pm, Paul Rubin wrote:
    tkp... at gmail.com writes:
    RVDict= {'1': random.betavariate(1,1), '2': random.expovariate(1), ...}
    This actually calls the functions random.betavariate, etc. when
    initializing RVDict. If you print out the contents of RVDict you'll see
    that each value in it is just a floating point number, not a callable.

    You want something like:

    RVDict = {'1': lambda: random.betavariate(1,1),
    '2': lambda: random.expovariate(1), etc.
    In Python 2.5, you can also write this as:

    from functools import partial

    RVDict = {'1': partial(random.betavariate,1,1),
    '2': partial(random.expovariate,1),
    etc.


    George
  • Tkpmep at Mar 31, 2008 at 1:17 am
    Paul, George,

    Thanks a mill - the help is greatly appreciated.

    Thomas Philips

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedMar 30, '08 at 8:54p
activeMar 31, '08 at 1:17a
posts3
users2
websitepython.org

2 users in discussion

Tkpmep: 2 posts George Sakkis: 1 post

People

Translate

site design / logo © 2022 Grokbase