【发布时间】:2018-11-02 15:17:17
【问题描述】:
我在 Python 上使用四阶 Runge-Kutta 编写了一段代码来求解 Lotka-Volterra 方程,但由于某种原因它不起作用,解完全错误。老实说,我不明白我做错了什么。
import numpy
from pylab import plot, show
def rk(f, x, h):
f_1 = f(x)
f_2 = f(x+1./2*h*f_1)
f_3 = f(x+1./2*h*f_2)
f_4 = f(x+h*f_3)
return x+1./6*h*(f_1+2*f_2+2*f_3+f_4)
def lv(x):
alpha = 1.
return numpy.array([alpha*x[0]-x[0]*x[1], x[0]*x[1]-x[1]], float)
a = 0.
b = 10.
m = 100
T = numpy.linspace(a, b, m)
H = (b-a)/m
X = numpy.zeros((m, 2))
X[0, :] = [1., 30.]
for i in range(1, m):
X[i, :] = rk(lv, X[i-1, :], H)
plot(T, X)
show()
非常感谢您的帮助。
【问题讨论】:
-
你认为结果在什么意义上是错误的?请注意,您的时间离散化步骤是
(b-a)/(m-1),请检查T[1]-T[0]。
标签: python python-2.7 ode