我正在尝试使用本书Finite Difference Computing with PDEs - A Modern Software Approach第5页中给出的有限差分法求解ODE。
import numpy as np
def solver(I, w, dt, T):
"""
Solve u'' + w ** 2 * u = 0 for t in (0, T], u(0) = I and u'(0) = 0,
by a central finite difference method with time step dt.
"""
dt = float(dt)
Nt = int(round(T / dt))
u = np.zeros(Nt + 1)
t = np.linspace(0, Nt * dt, Nt + 1)
u[0] = I
u[1] = u[0] - 0.5 * dt ** 2 * w ** 2 * u[0]
for n in range(1, Nt):
u[n+1] = 2 * u[n] - u[n-1] - dt ** 2 * w ** 2 * u[n]
return u, t
def main():
I = 1
w = 2 * np.pi
dt = 0.05
num_periods = 5
P = 2 * np.pi / w
T = P * num_periods
u, t = solver(I, w, dt, T)
我想知道是否有一种方法可以不使用for循环来更新u [2:]元素。我尝试过:
u[2:] = 2 * u[1:-1] - u[0:-2] - dt ** 2 * omega ** 2 * u[1:-1]
并且很明显,事实上,由于元素尚未更新,它不起作用。 here提出了一个非常类似的问题,但我不确定该答案是否可以用于此特定问题。