lundi 1 mars 2021

Numpy random number generators and lambda functions [duplicate]

I'm trying to create a list of random variables wtfuns that I can call as: wtfuns[i](size=1000) to return a list of 1000 samples of the particular random variable. For this, I am using lambda functions as follows:

wtfuns = []
pvals = [0.3,0.5,0.7]
for p in pvals:
    wtfuns.append(('bernoulli p='+str(p),lambda **x: binom(p,**x)))

for i in range(3):
    print(wtfuns[i][1](size=1000).mean())

Output

0.686
0.684
0.706

That is, in the column wtfuns[:,1] I have the same binomial random variable with parameter 0.7. However,

for p in pvals:
    print(wtfuns[0][1](size=1000).mean())

produces

0.311
0.524
0.67

Somehow the p value is being passed to the lambda function by reference. What is going on? I'm completely confused.




Aucun commentaire:

Enregistrer un commentaire