epx*_*epx 1 python random python-2.7
这是事情。
我想以不同的概率生成两个值,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()
Run Code Online (Sandbox Code Playgroud)
您收到消息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
Run Code Online (Sandbox Code Playgroud)
您可以通过更改import random as r为来修复您的代码import numpy.random as r,但是使用非标准的单字母名称来引用重要的模块只会使事情更加混乱。常规的缩写是
import numpy as np
Run Code Online (Sandbox Code Playgroud)
之后np.random.choice工作。
现在不可否认,因为scipy导入了 的一部分numpy,您可以numpy.random通过它访问,但是您的线路
from scipy import * # <-- don't do this!
Run Code Online (Sandbox Code Playgroud)
应该避免。它破坏了具有numpy不同行为的版本的标准 Python 函数,并且在某些情况下给出了相反的答案。
| 归档时间: |
|
| 查看次数: |
3955 次 |
| 最近记录: |