如何在scipy odeint中包含派生词?

时间:2013-11-13 17:52:47

标签: python odeint

当我在一个简单的微分方程中包含一个导数函数时,我会得到一长串的错误,如下面的代码所示。我做错了什么?

import numpy as np
from scipy.misc import derivative
from scipy.integrate import odeint

Imag = 16000.
w = 2*np.pi*60
tau = .05
theta = 1.52
phi = theta - np.radians(90)
t = np.linspace(0,.1,10000)
Ip = np.sqrt(2)*Imag*(np.sin(w*t+phi-theta)-np.exp(-t/tau)*np.sin(phi-theta))

def dI(t):
    return derivative(Ip,t)

def f(y,t):
    Rb = 8.
    N = 240.
    Is = y[0]
    f0 = (dI(t)/N)-Rb*y[0]
    return [f0]

yinit = [0]
sol = odeint(f,yinit,t)
print sol[:,0]

错误输出的一小部分似乎重复了几次,如下所示:

val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: 'numpy.ndarray' object is not callable
odepack.error: Error occurred while calling the Python function named f

编辑:上面的代码在scipy 0.9.0中运行没有错误,但在0.12.0中给出了上述错误

Edit2:既然已经处理了错误,我需要在积分器中添加第二个函数,如下所示:

B = lambda Ip: Ip/(53.05+0.55*abs(Ip))
L = lambda Ip: derivative(B,Ip)*377.2

def f(y,t):
    Rb = 8.
    N = 240.
    Is = y[0]
    f0 = (1/(L+0.002))*((dI(t)*L/N)-Rb*y[0])
    return [f0]

我该怎么做?

1 个答案:

答案 0 :(得分:1)

derivative的第一个参数必须是函数而不是ndarray。因此,您必须使用函数ndarray替换Ip Ip

以下例子适用于Python3

import numpy as np
from scipy.misc import derivative
from scipy.integrate import odeint

def Ip(t):
    return np.sqrt(2)*Imag*(np.sin(w*t+phi-theta)-np.exp(-t/tau)*np.sin(phi-theta))

Imag = 16000.
w = 2*np.pi*60
tau = .05
theta = 1.52
phi = theta - np.radians(90)
t = np.linspace(0,.1,10000)

def dI(t):
    return derivative(Ip,t)

def f(y,t):
    Rb = 8.
    N = 240.
    Is = y[0]
    f0 = (dI(t)/N)-Rb*y[0]
    return [f0]

yinit = [0]
sol = odeint(f,yinit,t)
print(sol[:,0])