Python 将循环结果保存到矩阵中
我目前正在编写一个Python工具,用于执行几何布朗运动。执行运动的循环已完成并按预期工作。现在,我很难将模拟的各种结果保存在一个大矩阵中,然后绘制它 我尝试使用append函数,但结果是,我得到的结果是一个列表,每个模拟都有另一个数组,而不是一个大矩阵 我的代码:Python 将循环结果保存到矩阵中,python,arrays,list,numpy,Python,Arrays,List,Numpy,我目前正在编写一个Python工具,用于执行几何布朗运动。执行运动的循环已完成并按预期工作。现在,我很难将模拟的各种结果保存在一个大矩阵中,然后绘制它 我尝试使用append函数,但结果是,我得到的结果是一个列表,每个模拟都有另一个数组,而不是一个大矩阵 我的代码: import matplotlib.pyplot as plt import numpy as np T = 2 mu = 0.15 sigma = 0.10 S0 = 20 dt = 0.01 N = round(T/dt)
import matplotlib.pyplot as plt
import numpy as np
T = 2
mu = 0.15
sigma = 0.10
S0 = 20
dt = 0.01
N = round(T/dt) ### Paths
simu = 20 ### number of simulations
i = 1
## creates an array with values from 0 to T with N elementes (T/dt)
t = np.linspace(0, T, N)
## empty Matrix for the end results
res = []
while i < simu + 1:
## random number showing the Wiener process
W = np.random.standard_normal(size = N)
W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###
X = (mu-0.5*sigma**2)*t + sigma*W
S = S0*np.exp(X) ### new Stock prices based on the simulated returns ###
res.append(S) #appends the resulting array to the result table
i += 1
#plotting of the result Matrix
plt.plot(t, res)
plt.show()
导入matplotlib.pyplot作为plt
将numpy作为np导入
T=2
mu=0.15
西格玛=0.10
S0=20
dt=0.01
N=圆形(T/dt)####路径
simu=20###模拟次数
i=1
##创建一个值为0到T的数组,其中包含N个元素(T/dt)
t=np.linspace(0,t,N)
##最终结果的空矩阵
res=[]
而i
如果有人能帮我解决这个问题,我会非常高兴,因为我打算用不同的路径(存储在大矩阵中)来绘制时间
提前谢谢大家,
Nick要完全避免循环,并使用快速、干净的pythonic向量化操作,您可以这样编写操作:
import matplotlib.pyplot as plt
import numpy as np
T = 2
mu = 0.15
sigma = 0.10
S0 = 20
dt = 0.01
N = round(T/dt) ### Paths
simu = 20 ### number of simulations
i = 1
## creates an array with values from 0 to T with N elementes (T/dt)
t = np.linspace(0, T, N)
## result matrix creation not needed, thanks to gboffi for the hint :)
## random number showing the Wiener process
W = np.random.standard_normal(size=(simu, N))
W = np.cumsum(W, axis=1)*np.sqrt(dt) ### standard brownian motion ###
X = (mu-0.5*sigma**2)*t + sigma*W
res = S0*np.exp(X) ### new Stock prices based on the simulated returns ###
现在,您的结果存储在实矩阵中,或者正确地存储在np.ndarray
中np.ndarray
是numpy
的标准数组格式,因此是最广泛使用和支持的数组格式。要绘制它,您需要提供进一步的信息,例如:是否要绘制结果数组的每一行?这将看起来像:
for i in range(simu):
plt.plot(t, res[i])
plt.show()
如果要在计算后检查形状的一致性,可以执行以下操作:
assert res.shape == (simu, N), 'Calculation faulty!'
尝试使用as方法。这将另一个iterable对象作为参数,并将此参数中的每个元素追加到列表中。有关更多信息,请参阅。
i
在while
循环中不使用,除了递增。这是不良设计的明显迹象。这种循环是完全可以避免的。您还可以预先知道将生成多少元素。哦,顺便说一句:res
是一个列表,而不是一个矩阵!我的解决方案解决了你的问题吗?嗨,尼克,我的解决方案解决了你的问题吗?如果是,请投赞成票。如果没有,请告诉我什么不起作用,以便我可以改进它。res=np.zeros((20200))
将名称res
分配给一个20x200数组,该数组由零填充,然后下一个res=S0*np.exp(X)
将名称res
分配给表达式的值S0*np.exp(X)
,当零数组将被垃圾收集时。。。很浪费,不是吗?没错。这并不是故意的,只是想向OP展示如何创建一个数组而不是一个列表。因此,要么省略res=np.zeros((20200))
,要么创建一个空数组并为其赋值(如我的答案所示)。创建一个空数组并分配值可能会稍微慢一点,但由于给定的结果形状,这会使查找错误计算变得更容易。拜托,不要找借口。。。请漂亮,请删除零数组创建:这绝对不是Numpy,我敢说这是FORTRAN66 ly!!!哈哈,好的。我只为你把它取下来!;)为了仍然实现检查,我将再添加一行进行检查。