使用scipy.integrate.odeint求解微分方程时遇TypeError问题求助
解决scipy.integrate.odeint中的TypeError: 'float' object is not callable错误
我是Python新手,尝试使用scipy.integrate.odeint求解微分方程,但始终遇到TypeError: 'float' object is not callable错误,无法让odeint正常工作。
我的代码如下:
import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import CubicSpline from scipy.integrate import odeint from math import * # Define parameters alpha = 52.875 beta = 13.345 gamma = -1.44 delta = 2.29 # Define model def model(h,t,om): halflife = alpha - (beta(-delta+gamma*om)) k = log(2)/halflife dherb_dt = -kh return dherb_dt # Initial condition h0 = 4.271 # mg/kg, assuming a 2.67 pt/acre application of Dual II Magnum # Time, in days, to interpolate over t = np.linspace(0, 20) # Solve ODE om = 2.5 y1 = odeint(model, h0, t, args=(om,)) # Plot plt.plot(t,y1) plt.xlabel("Months") plt.ylabel("Dose") plt.show()
错误信息:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [17], in <cell line: 22>() 20 # Solve ODE 21 om = 2.5 ---> 22 y1 = odeint(model, h0, t, args=(om,)) 24 # Plot 25 plt.plot(t,y1) File ~\anaconda3\envs\agron893\lib\site-packages\scipy\integrate\_odepack_py.py:241, in odeint(func, y0, t, args, Dfun, col_deriv, full_output, ml, mu, rtol, atol, tcrit, h0, hmax, hmin, ixpr, mxstep, mxhnil, mxordn, mxords, printmessg, tfirst) 239 t = copy(t) 240 y0 = copy(y0) ---> 241 output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu, 242 full_output, rtol, atol, tcrit, h0, hmax, hmin, 243 ixpr, mxstep, mxhnil, mxordn, mxords, 244 int(bool(tfirst))) 245 if output[-1] < 0: 246 warning_msg = _msgs[output[-1]] + " Run with full_output = 1 to get quantitative information." Input In [17], in model(h, t, om) 8 def model(h,t,om): ----> 9 halflife = alpha - (beta(-delta+gamma*om)) 10 k = log(2)/halflife 11 dherb_dt = -kh TypeError: 'float' object is not callable
修复方案
错误核心是Python中乘法不能省略运算符,你在两处代码里遗漏了*号:
beta(-delta+gamma*om):beta是float变量,被误当作函数调用,正确写法为beta * (-delta + gamma*om)-kh:k和h之间缺少乘法运算符,正确写法为-k * h
修改后的完整代码:
import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import CubicSpline from scipy.integrate import odeint from math import * # Define parameters alpha = 52.875 beta = 13.345 gamma = -1.44 delta = 2.29 # Define model def model(h,t,om): halflife = alpha - (beta * (-delta + gamma*om)) # 修复乘法运算符 k = log(2)/halflife dherb_dt = -k * h # 修复乘法运算符 return dherb_dt # Initial condition h0 = 4.271 # mg/kg, assuming a 2.67 pt/acre application of Dual II Magnum # Time, in days, to interpolate over t = np.linspace(0, 20) # Solve ODE om = 2.5 y1 = odeint(model, h0, t, args=(om,)) # Plot plt.plot(t,y1) plt.xlabel("Days") # 建议改为Days,与t的单位一致 plt.ylabel("Dose") plt.show()
内容的提问来源于stack exchange,提问作者s_o_c_account
相关产品推荐
相关产品推荐

