代码与前几行相同但给出错误?
Code is the same as previous lines but gives an error?
我不断收到
TypeError: 'int' object is not subscriptable
在我的 evenly() 函数中。如果我注释掉 evenly 函数,equall() 和 gauss() 工作正常,我所做的只是从它们复制代码并使用我的 stepe() 函数而不是 step() 或 stepn()
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import rand,seed,randn
steps = 1
walks = 10000
walk = np.zeros(steps + 1)
def step():
if rand() < 0.5:
return 1.0
return -1.0
def stepn():
return randn() + 0.5
def stepe():
return (6*(rand()-0.5))
def equall(walks,steps):
l = []
for w in range(walks):
for s in range(steps):
walk[s+1] = walk[s] + step()
l.append(walk[steps])
return l
def gauss(walks,steps):
l = []
for w in range(walks):
for s in range(steps):
walk[s+1] = walk[s] + stepn()
l.append(walk[steps])
return l
def evenly(walk,steps):
l = []
for w in range(walks):
for s in range(steps):
walk[s+1] = walk[s] + stepn()
l.append(walk[steps])
return l
plt.figure(figsize=(10,7))
plt.hist(equall(walks,steps),bins=15)
plt.show()
plt.hist(gauss(walks,steps),bins=15)
plt.show()
plt.hist(evenly(walks,steps),bins=15)
plt.show()
def evenly(walk,steps):
这里的参数walk
(而不是walks
)屏蔽了同名的外部变量,并为后续语句walk[s+1] = walk[s] + stepn()
定义。我猜应该是walks
我不断收到
TypeError: 'int' object is not subscriptable
在我的 evenly() 函数中。如果我注释掉 evenly 函数,equall() 和 gauss() 工作正常,我所做的只是从它们复制代码并使用我的 stepe() 函数而不是 step() 或 stepn()
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import rand,seed,randn
steps = 1
walks = 10000
walk = np.zeros(steps + 1)
def step():
if rand() < 0.5:
return 1.0
return -1.0
def stepn():
return randn() + 0.5
def stepe():
return (6*(rand()-0.5))
def equall(walks,steps):
l = []
for w in range(walks):
for s in range(steps):
walk[s+1] = walk[s] + step()
l.append(walk[steps])
return l
def gauss(walks,steps):
l = []
for w in range(walks):
for s in range(steps):
walk[s+1] = walk[s] + stepn()
l.append(walk[steps])
return l
def evenly(walk,steps):
l = []
for w in range(walks):
for s in range(steps):
walk[s+1] = walk[s] + stepn()
l.append(walk[steps])
return l
plt.figure(figsize=(10,7))
plt.hist(equall(walks,steps),bins=15)
plt.show()
plt.hist(gauss(walks,steps),bins=15)
plt.show()
plt.hist(evenly(walks,steps),bins=15)
plt.show()
def evenly(walk,steps):
这里的参数walk
(而不是walks
)屏蔽了同名的外部变量,并为后续语句walk[s+1] = walk[s] + stepn()
定义。我猜应该是walks