gpt4 book ai didi

python - Python 中 scipy.integrate 的 odeint 给出了错误的结果?

转载 作者:太空宇宙 更新时间:2023-11-04 10:27:05 25 4
gpt4 key购买 nike

我正在尝试求解 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 做错了什么?

最佳答案

函数参数在 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()

关于python - Python 中 scipy.integrate 的 odeint 给出了错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28780770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com