Python使用odeint报错:takes 1 positional argument but 2 were given
问题解决:odeint报错“takes 1 positional argument but 2 were given”
问题出在你定义的sy函数参数数量不符合odeint的要求。scipy的odeint在调用被积分的函数时,会自动传入两个参数:
- 第一个是状态向量(也就是你的
J) - 第二个是当前的时间点
t,哪怕你的微分方程不依赖时间,这个参数也必须存在
你的sy函数只定义了一个参数J,所以当odeint尝试传入第二个参数t时,就会触发参数数量不匹配的报错。
修复后的代码
def sy(J, t): # 新增t参数,哪怕函数内部不用它 Ntot = J[0] xb = J[1] dNtotdt = nn2 - nv dxbdt = (-nv*xb - xb*dNtotdt)/Ntot return [dNtotdt, dxbdt] # odeint requires that we set up a vector of times (question asks for 0-10) t_val = np.linspace(0,10,46) #46 for more accuracy # we also need to make an initial condition vector Yo = np.array([Ntoto, xbo]) # use odient function to find the concentrations ans = odeint(sy, Yo, t_val) print(ans)
补充说明
如果你的微分方程确实需要依赖时间,直接在函数内部使用t即可;如果不需要,保留t参数但不用它就好。另外注意确保nn2、nv、Ntoto、xbo这些变量已经在函数外部正确定义,否则可能会出现其他报错。
内容的提问来源于stack exchange,提问作者afg
相关产品推荐
相关产品推荐

