为什么这两个ODE解决程序不匹配?

时间:2019-07-23 22:29:53

标签: python python-3.x ode odeint

我不明白为什么这样的代码(reference):

from numpy import zeros, linspace
import matplotlib.pyplot as plt

# Time unit: 1 h
beta = 10./(40*8*24)
gamma = 3./(15*24)
dt = 0.1             # 6 min
D = 30               # Simulate for D days
N_t = int(D*24/dt)   # Corresponding no of hours

t = linspace(0, N_t*dt, N_t+1)
S = zeros(N_t+1)
I = zeros(N_t+1)
R = zeros(N_t+1)

# Initial condition
S[0] = 50
I[0] = 1
R[0] = 0

# Step equations forward in time
for n in range(N_t):
    S[n+1] = S[n] - dt*beta*S[n]*I[n]
    I[n+1] = I[n] + dt*beta*S[n]*I[n] - dt*gamma*I[n]
    R[n+1] = R[n] + dt*gamma*I[n]

fig = plt.figure()
l1, l2, l3 = plt.plot(t, S, t, I, t, R)
fig.legend((l1, l2, l3), ('S', 'I', 'R'), 'upper left')
plt.xlabel('hours')
plt.show()

不会产生与我编写的代码相同的结果:

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt


beta = 10. / (40 * 8 * 24)
gamma = 3. / (15 * 24)


def flu(y, t):
    S = y[0]
    P = y[1]
    R = y[2]

    S = - beta * S * P
    P = beta * S * P - gamma * P
    R = gamma * P

    return [S, P, R]


C_I = [50, 1, 0]
t = np.linspace(0, 1000, 1000)

y = odeint(flu, C_I, t)

S = y[:, 0]
P = y[:, 1]
R = y[:, 2]

fig, ax = plt.subplots()
ax.plot(t, S, 'b--', label='S')
ax.plot(t, P, 'r--', label='I')
ax.plot(t, R, 'g--', label='R')
legend = ax.legend(loc='upper right', shadow=True, fontsize='x-large')
legend.get_frame().set_facecolor('#FFFCCC')
plt.show()

为了避免混淆,我使用了P而不是I。

用odeint求解的方程应与以上参考链接中提供的方程相同。如果我确信所使用的方程式是正确的,那么我不知道错误在哪里。

谢谢您的帮助

1 个答案:

答案 0 :(得分:1)

先设置S=y[0],然后再设置S=- beta * S * P。这将覆盖y [0]! PR

的类似问题

尝试一下:

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt


beta = 10. / (40 * 8 * 24)
gamma = 3. / (15 * 24)


def flu(y, t):
    S = y[0]
    P = y[1]
    R = y[2]

    dS = - beta * S * P
    dP = beta * S * P - gamma * P
    dR = gamma * P

    return [dS, dP, dR]


C_I = [50, 1, 0]
t = np.linspace(0, 1000, 1000)

y = odeint(flu, C_I, t)

S = y[:, 0]
P = y[:, 1]
R = y[:, 2]

fig, ax = plt.subplots()
ax.plot(t, S, 'b--', label='S')
ax.plot(t, P, 'r--', label='I')
ax.plot(t, R, 'g--', label='R')
legend = ax.legend(loc='upper right', shadow=True, fontsize='x-large')
legend.get_frame().set_facecolor('#FFFCCC')
plt.show()