我正在尝试求解三阶非线性微分方程。我试图改变它,我得到了这个问题,这是一个二阶问题:
我正在尝试实现四阶 Range-Kutta 算法,以便通过这样编写来解决它:
这是我的 Range-Kutta 算法代码:
import numpy as np
import matplotlib.pyplot as plt
''''X,Y = integrate(F,x,y,xStop,h).
4th-order Runge-Kutta method for solving the initial value problem {y}' = {F(x,{y})}, where {y} = {y[0],y[1],...,y[n-1]}.
x,y = initial conditions
xStop = terminal value of x
h = increment of x used in integration
F = user-supplied function that returns the
array F(x,y) = {y'[0],y'[1],...,y'[n-1]}.
'''
def integrate(F,x,y,xStop,h):
def run_kut4(F,x,y,h):
K0 = h*F(x,y)
K1 = h*F(x + h/2.0, y + K0/2.0)
K2 = h*F(x + h/2.0, y + K1/2.0)
K3 = h*F(x + h, y + K2)
return (K0 + 2.0*K1 + 2.0*K2 + K3)/6.0
X =[]
Y =[]
X.append(x)
Y.append(y)
while x < xStop:
h = min(h,xStop - x)
y = y + run_kut4(F,x,y,h)
x = x + h
X.append(x)
Y.append(y)
return np.array(X),np.array(Y)
它适用于其他微分方程。
在这种情况下,函数 F 定义为:
主要代码是:
def F(x,y):
F = np.zeros(2)
F[0] = y[1]
F[1] = (2*(1-x)/x**3)*y[0]**(-1/2)
return F
x = 1.0
xStop = 20
y = np.array([0,0])
h = 0.2
X,Y = integrate(F,x,y,xStop,h)
plt.plot(X,Y)
plt.grid()
plt.show()
不幸的是,我收到了这个错误:
<ipython-input-8-8216949e6888>:4: RuntimeWarning: divide by zero encountered in power
F[1] = (2*(1-x)/x**3)*y[0]**(-1/2)
<ipython-input-8-8216949e6888>:4: RuntimeWarning: divide by zero encountered in double_scalars
F[1] = (2*(1-x)/x**3)*y[0]**(-1/2)
这与函数的初始值为0的事实有关,但我不知道如何摆脱它以便再次简化问题......
有人可以帮我找到其他选择吗?
谢谢您的帮助,