以不等概率生成数字

时间:2015-01-25 06:52:25

标签: python python-2.7 random

这就是事情。

我想以不同的概率生成两个值1和-1。 当我运行这个脚本时,我收到消息“choice()得到了一个意外的关键字参数'p'”

有人能告诉我为什么会这样,以及如何解决这个问题? 感谢。

from scipy import *
import matplotlib.pyplot as plt
import random as r

def ruin_demo():


    tmax = 1000       #The number of game rounds
    Xi = 10           #The initial money the gambler has
    T = []
    M = []
    t = 1
    for N in linspace(0.3, 0.49, 100):     #The probability changing region

        meandeltaX = 1.0*N + (1-N)*(-1.0)  #The expected value for each game round
        M.append(meandeltaX)
        while (t < tmax and Xi > 0):

            deltaX  = r.choice((1, -1), p=[N, 1-N]) # The change of money during each game round
                #print deltaX
            Xi = Xi + deltaX
            t = t + 1
        T.append(t)
    plt.plot(M, T)
    plt.show()

ruin_demo()

1 个答案:

答案 0 :(得分:4)

您收到消息TypeError: choice() got an unexpected keyword argument 'p',因为random.choice(Python标准库函数)没有关键字参数p

可能你的意思是numpy.random.choice

>>> numpy.random.choice((1,-1), p=[0.2, 0.8])
-1

您可以通过将import random as r更改为import numpy.random as r来修复代码,但使用非标准的单字母名称来引用一个重要的模块只会让事情更加混乱。传统的缩写是

import numpy as np

之后np.random.choice有效。


现在无可否认,因为scipy导入numpy的一部分,您可以通过它访问numpy.random,但是您的行

from scipy import *   # <-- don't do this! 

应该避免。它破坏了numpy版本的标准Python函数,这些函数的行为不同,在某些情况下给出相反的答案。