【问题标题】:TypeError: model() takes exactly 3 arguments (5 given)TypeError: model() 正好需要 3 个参数(给定 5 个)
【发布时间】:2016-07-16 11:56:48
【问题描述】:

odeint 与以下设置工作正常;

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

v0 = 10.0
k1 = 0.5
k2 = 0.35

def model(x,t):
    dx0 = v0 - k1*x[0]
    dx1 = k1*x[0] - k2*x[1]
    return [dx0, dx1]
time = linspace(0.0,20.0,100)
xinit = array([0.0,0.0])
x = odeint(model,xinit,time)
plt.plot(time, x[:,0], time, x[:,1])

但是当我想定义一个参数化模型,然后将参数传递给 model() 函数时,当 odeint 调用它时,我遇到了这个错误:TypeError: model() 恰好需要 3 个参数(给定 5 个) .这里有什么问题?传递参数的正确设置是什么?

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def model (x,t,p):
    dot_x = np.zeros(2)
    v0 = p[0]
    k1 = p[1]
    k2 = p[2]
    dot_x[0] = v0 - k1*x[0]
    dot_x[1] = k1*x[0] - k2*x[1]
    return dot_x

p = (10,0.5,.35)
xinit = [0.0,0.0] 
time = linspace(0.0,20.0,100)

x = odeint(model,xinit,time,p)

plt.plot(time, x[:,0], time, x[:,1])

【问题讨论】:

  • 将参数p作为参数传递,即def model(x,t,*args):
  • @Thiru 谢谢。效果很好!

标签: python scipy odeint


【解决方案1】:

感谢 Thiru 的评论,这是解决方案:

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def model (x,t,*p):
    dot_x = np.zeros(2)
    v0 = p[0]
    k1 = p[1]
    k2 = p[2]
    dot_x[0] = v0 - k1*x[0]
    dot_x[1] = k1*x[0] - k2*x[1]
    return dot_x

p = (10,0.5,.35)
xinit = [0.0,0.0] 
time = linspace(0.0,20.0,100)

x = odeint(model,xinit,time,p)

plt.plot(time, x[:,0], time, x[:,1])

【讨论】:

    猜你喜欢
    • 2012-03-15
    • 2014-05-06
    • 2014-05-31
    • 2013-06-12
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多