切换odeint至solve_ivp求解器时出现'float' object is not subscriptable错误求助
问题解决:solve_ivp替换odeint时的'float' object is not subscriptable错误
原问题代码
def tank(h,t): c1=0.13 c2=0.20 Ac=2.0 qin=0.5 h0=h[0] h1=h[1] qout1=c1*h0**0.5 qout2=c2*h1**0.5 dhdt1=(qin-qout1)/Ac dhdt2=(qout1-qout2)/Ac dhdt=[dhdt1,dhdt2] return dhdt t0=0 tfinal=100 tspan=np.arange(0,tfinal+1) y0=np.array([0,0]) # t=np.linspace(0,10,21) # y=odeint(tank,y0,t,) y=solve_ivp(tank,(t0,tfinal),y0,t_eval=tspan) print(y) plt.plot(t,y[:,0],'b-') plt.plot(t,y[:,1],'r--') plt.show()
修正后的代码
import numpy as np from scipy.integrate import solve_ivp, odeint import matplotlib.pyplot as plt def tank(t, h): # 调整参数顺序为t在前,h在后 c1=0.13 c2=0.20 Ac=2.0 qin=0.5 h0=h[0] h1=h[1] qout1=c1*h0**0.5 qout2=c2*h1**0.5 dhdt1=(qin-qout1)/Ac dhdt2=(qout1-qout2)/Ac dhdt=[dhdt1,dhdt2] return dhdt t0=0 tfinal=100 tspan=np.arange(0,tfinal+1) y0=np.array([0,0]) # t=np.linspace(0,10,21) # y=odeint(tank,y0,t,) y=solve_ivp(tank,(t0,tfinal),y0,t_eval=tspan) print(y) plt.plot(tspan,y.y[0],'b-') # 调整y的索引方式,solve_ivp返回的y是行向量 plt.plot(tspan,y.y[1],'r--') plt.show()
错误原因
- 参数顺序不匹配:
solve_ivp要求微分方程函数的参数顺序为(t, y),而odeint是(y, t)。原函数参数顺序错误,导致h被传入单个float值,无法进行下标访问(如h[0]),从而触发'float' object is not subscriptable错误。 - 结果索引方式错误:
solve_ivp返回的结果中,y是行向量结构(存储为y.y),而非odeint返回的列向量,因此需要调整索引方式为y.y[0]、y.y[1],同时绘图时要使用定义好的tspan而非未定义的t。
内容的提问来源于stack exchange,提问作者Nis
相关产品推荐
相关产品推荐

