【发布时间】:2020-02-23 10:40:23
【问题描述】:
我目前正在尝试编写一些 python 代码来解决任意一阶 ODE 系统,使用由值 alpha、gamma(两个维度为 m)和 beta(下三角矩阵)定义的通用显式 Runge-Kutta 方法由用户传入的 Butcher 表的尺寸为 m x m)。我的代码似乎适用于单个 ODE,并在几个不同的示例上对其进行了测试,但我正在努力将我的代码推广到向量值 ODE(即系统)。
特别是,我尝试使用由我的代码中给出的 Butcher Tableau 值定义的 Heun 方法求解范德波尔振荡器 ODE(简化为一阶系统),但我收到错误
- “RuntimeWarning:double_scalars
f = lambda t,u: np.array(... etc)中遇到溢出”和- “RuntimeWarning:添加
kvec[i] = f(t+alpha[i]*h,y+h*sum)时遇到无效值”
紧随其后的是我的解决方案向量,它显然正在爆炸。请注意,下面注释掉的代码是我尝试并正确解决的单个 ODE 示例之一。有人可以帮忙吗?这是我的代码:
import numpy as np
def rk(t,y,h,f,alpha,beta,gamma):
'''Runga Kutta iteration'''
return y + h*phi(t,y,h,f,alpha,beta,gamma)
def phi(t,y,h,f,alpha,beta,gamma):
'''Phi function for the Runga Kutta iteration'''
m = len(alpha)
count = np.zeros(len(f(t,y)))
kvec = k(t,y,h,f,alpha,beta,gamma)
for i in range(1,m+1):
count = count + gamma[i-1]*kvec[i-1]
return count
def k(t,y,h,f,alpha,beta,gamma):
'''returning a vector containing each step k_{i} in the m step Runga Kutta method'''
m = len(alpha)
kvec = np.zeros((m,len(f(t,y))))
kvec[0] = f(t,y)
for i in range(1,m):
sum = np.zeros(len(f(t,y)))
for l in range(1,i+1):
sum = sum + beta[i][l-1]*kvec[l-1]
kvec[i] = f(t+alpha[i]*h,y+h*sum)
return kvec
def timeLoop(y0,N,f,alpha,beta,gamma,h,rk):
'''function that loops through time using the RK method'''
t = np.zeros([N+1])
y = np.zeros([N+1,len(y0)])
y[0] = y0
t[0] = 0
for i in range(1,N+1):
y[i] = rk(t[i-1],y[i-1], h, f,alpha,beta,gamma)
t[i] = t[i-1]+h
return t,y
#################################################################
'''f = lambda t,y: (c-y)**2
Y = lambda t: np.array([(1+t*c*(c-1))/(1+t*(c-1))])
h0 = 1
c = 1.5
T = 10
alpha = np.array([0,1])
gamma = np.array([0.5,0.5])
beta = np.array([[0,0],[1,0]])
eff_rk = compute(h0,Y(0),T,f,alpha,beta,gamma,rk, Y,11)'''
#constants
mu = 100
T = 1000
h = 0.01
N = int(T/h)
#initial conditions
y0 = 0.02
d0 = 0
init = np.array([y0,d0])
#Butcher Tableau for Heun's method
alpha = np.array([0,1])
gamma = np.array([0.5,0.5])
beta = np.array([[0,0],[1,0]])
#rhs of the ode system
f = lambda t,u: np.array([u[1],mu*(1-u[0]**2)*u[1]-u[0]])
#solving the system
time, sol = timeLoop(init,N,f,alpha,beta,gamma,h,rk)
print(sol)
【问题讨论】:
-
count = np.zeros(len(y)),类似kvec = np.zeros((m,len(y))),应该够用了,如果有尺寸不匹配会导致下一步出错。f的评估被认为是“昂贵的”。
标签: python numerical-methods ode differential-equations runge-kutta