For loop 环路模拟
我试图模拟以下随机行走方程: 但是,当我运行代码时,我不能附加结果。我得到以下错误: first_term=results[i]TypeError:“非类型”对象不是 可下标 有没有其他办法For loop 环路模拟,for-loop,statistics,time-series,simulation,random-walk,For Loop,Statistics,Time Series,Simulation,Random Walk,我试图模拟以下随机行走方程: 但是,当我运行代码时,我不能附加结果。我得到以下错误: first_term=results[i]TypeError:“非类型”对象不是 可下标 有没有其他办法 import numpy as np import pandas as pd def simulation(x0, T, sigma, p): results = [x0] prob_e = [p, (1-p)] values_e = [1, -1] for i in r
import numpy as np
import pandas as pd
def simulation(x0, T, sigma, p):
results = [x0]
prob_e = [p, (1-p)]
values_e = [1, -1]
for i in range(T):
first_term = results[i]
error = np.random.choice(values_e, 1, prob_e)
second_term = sigma * error
result = first_term + second_term
results = results.append(result)
return results
print(simulation(10, 120, 0.6, 0.5))
在循环的最后一行,应该是
results.append(result)
,而不是results=results.append(result)
results
是一个列表对象,而append
函数修改该对象,返回None
是一件很棒的事情。在介绍课程中缺乏对它们的覆盖是IMHO的一大失败。