【问题标题】:odeint from scipy.integrate in Python giving wrong result?Python 中 scipy.integrate 中的 odeint 给出错误结果?
【发布时间】:2015-02-28 19:25:40
【问题描述】:

我正在尝试使用以下代码解决 ivp y'=-y-5 * exp(-t) * sin(5 t), y(0)=1:

%pylab inline
%matplotlib inline
from scipy.integrate import odeint

def mif(t, y):
    return -y-5*exp(-t)*sin(5*t)

tspan = np.arange(0, 3, 0.000001)
y0 = 1.0
y_result = odeint(mif, y0, tspan)
y_result = y_result[:, 0]  # convert the returned 2D array to a 1D array
plt.figure()
plt.plot(tspan, y_result)
plt.show()

但是,我得到的情节是错误的,它与我使用 Matlab 或 Mathematica 获得的不符。它实际上不同于以下替代集成:

from scipy.integrate import ode

# initialize the 4th order Runge-Kutta solver
solver = ode(mif).set_integrator('dop853')

# initial value
y0 = 1.0
solver.set_initial_value(y0, 0)

values = 1000
t = np.linspace(0.0001, 3, values)
y = np.zeros(values)

for ii in range(values):
    y[ii] = solver.integrate(t[ii])[0] #z[0]=u

确实会产生正确的结果。我在 odeint 上做错了什么?

【问题讨论】:

    标签: python matlab scipy


    【解决方案1】:

    函数参数在 ode 和 odeint 之间变化。对于 odeint,您需要

    def mif(y, t):
    

    对于颂歌

    def mif(t, y):
    

    例如

    %pylab inline
    %matplotlib inline
    from scipy.integrate import odeint
    
    def mif(t,y):
        return y
    
    tspan = np.arange(0, 3, 0.000001)
    y0 = 0.0
    y_result = odeint(mif, y0, tspan)
    plt.figure()
    plt.plot(tspan, y_result)
    plt.show()
    

    from scipy.integrate import ode
    
    def mif(y, t):
        return y
    
    # initialize the 4th order Runge-Kutta solver
    solver = ode(mif).set_integrator('dop853')
    
    # initial value
    y0 = 0.000000
    solver.set_initial_value([y0], 0.0)
    
    values = 1000
    t = np.linspace(0.0000001, 3, values)
    y = np.zeros(values)
    
    for ii in range(values):
        y[ii] = solver.integrate(t[ii]) #z[0]=u
    plt.figure()
    plt.plot(t, y)
    plt.show()
    

    【讨论】:

    • 如果对您有帮助,请不要忘记接受@AndreiMF 的答案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2018-02-09
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多