以不等概率生成数字
Generating numbers with unequal probability
事情是这样的。
我想以不同的概率生成两个值,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()
您收到消息 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 函数,并且在某些情况下会给出相反的答案。
事情是这样的。
我想以不同的概率生成两个值,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()
您收到消息 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 函数,并且在某些情况下会给出相反的答案。