我正在尝试将一段MATLAB代码转换为Python3代码。
代码与Lotka-Volterra方程有关
这是MATLAB的原始代码
t0=0; tf=6*pi; eps=0.1; delta=0;
r=[1/2, 1, 2];
options = odeset(’RelTol’,1e-6,’AbsTol’,1.e-9);
%phase space plot
xpos=[2.5 2.5 2.5]; ypos=[3.5 3.5 3.5]
for i=1:length(r);
for eps=0.1:0.1:1.0;
[t,UV]=ode45(@(t,UV) lv_eq(t,UV,r(i)),[t0,tf],[1+eps 1+delta],options);
U=UV(:,1); V=UV(:,2);
figure(2);subplot(1,3,i); plot(U,V); hold on;
end
axis equal; axis([0 4 0 4]);
text(xpos(i),ypos(i),[’r=’,num2str(r(i))]);
if i==1; ylabel(’predator’); end;
xlabel(’prey’);
end
function dUV=lv_eq(t,UV,r)
dUV=zeros(2,1);
dUV(1) = r*(UV(1)-UV(1)*UV(2));
dUV(2) = (1/r)*(UV(1)*UV(2)-UV(2));
以下是我的Python3代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
from functools import partial
def lotka_volterra(t, X, r):
return np.array([r*(X[0]-X[0]*X[1]), (1/r)*(X[0]*X[1]-X[1])])
t0=0
tf=6*np.pi
prey_0 = 0.1
predator_0 = 0
rs = [0.5, 1, 2]
fig, axes = plt.subplots(ncols=3, sharey=True)
for i in range(len(rs)):
for prey_0 in np.arange(0.1, 1.0, 0.1):
f = partial(lotka_volterra, r=rs[i])
sol = integrate.solve_ivp(f, t_span=[t0, tf], y0=[1+prey_0, 1+predator_0], rtol=1e-6, atol=1.e-9)
U, V = sol.y
axes[i].plot(U, V)
axes[i].axis([0, 4, 0, 4])
axes[i].set_title('r='+str(rs[i]))
axes[i].set_xlabel('prey')
if i==0:
axes[i].set_ylabel('predator')
原始代码的输出为:
我的代码的输出是:
我不确定如何解决此问题。