我對一階微分方程組的x(t)數值求解。該系統是:向量化微分方程組的正向歐拉法
DX/DT = Y
DY/DT = -x - 一個* Y(X^2 + Y^2 -1)
我已經實現向前歐拉方法來解決這個問題如下:
def forward_euler():
h = 0.01
num_steps = 10000
x = np.zeros([num_steps + 1, 2]) # steps, number of solutions
y = np.zeros([num_steps + 1, 2])
a = 1.
x[0, 0] = 10. # initial condition 1st solution
y[0, 0] = 5.
x[0, 1] = 0. # initial condition 2nd solution
y[0, 1] = 0.0000000001
for step in xrange(num_steps):
x[step + 1] = x[step] + h * y[step]
y[step + 1] = y[step] + h * (-x[step] - a * y[step] * (x[step] ** 2 + y[step] ** 2 - 1))
return x, y
現在我想進一步向量化的代碼,並保持在同一陣列中的x和y,我已經提出了以下解決方案:
def forward_euler_vector():
num_steps = 10000
h = 0.01
x = np.zeros([num_steps + 1, 2, 2]) # steps, variables, number of solutions
a = 1.
x[0, 0, 0] = 10. # initial conditions 1st solution
x[0, 1, 0] = 5.
x[0, 0, 1] = 0. # initial conditions 2nd solution
x[0, 1, 1] = 0.0000000001
def f(x):
return np.array([x[1],
-x[0] - a * x[1] * (x[0] ** 2 + x[1] ** 2 - 1)])
for step in xrange(num_steps):
x[step + 1] = x[step] + h * f(x[step])
return x
的問題:forward_euler_vector()的作品,但這是最好的方式來矢量化它?我問,因爲矢量版本的運行約20毫秒在我的筆記本電腦慢:
In [27]: %timeit forward_euler()
1 loops, best of 3: 301 ms per loop
In [65]: %timeit forward_euler_vector()
1 loops, best of 3: 320 ms per loop
「向量化」版本只能實現向量化h * f(x [step])或者兩個操作。創建numpy數組的額外成本抵消了任何速度增益。根據你在做什麼,你可能想看看[scipy.integrate.ode](http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.ode.html#scipy.integrate。頌)。 – Daniel