Python 如何在scipy odeint中包含导数?

Python 如何在scipy odeint中包含导数?,python,odeint,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

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

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
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]
编辑:上述代码在scipy 0.9.0中运行时没有错误,但在0.12.0中给出了上述错误

Edit2:现在错误已经解决了,我需要在积分器中添加第二个函数,如下所示:

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
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]

怎么做?

导数的第一个参数必须是一个函数,而不是
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])

这里给出了一个示例:[这对我一点帮助都没有。我对该方法还不感兴趣。此时,我希望脚本运行时不会出现错误。感谢您的响应。这对我不起作用(python 2.7,scipy 0.9.0)。我收到以下错误:Traceback(最近的调用last):File“C:\Windows\system32\config\systemprofile\Desktop\ct_example.py”,第53行,在f f0=(dI(t)/N)-Rb*y[0]类型错误:不支持的操作数类型for/:'NoneType'和'float'odepack.error:调用名为fStrange的Python函数时出错,在我的计算机上它也使用Python 2.7和scipy 0.9运行。您的numpy版本是什么?也许,您应该将numpy和scipy更新为最新版本。我下载了最新版本的WinPython,代码运行良好。谢谢。抱歉,我不明白,你想达到什么目的。我想你应该为你的第二次编辑创建一个新问题,因为这个问题已经标记为已解决,没有人会再看它了。正如@Holger所建议的,我已经将它作为一个新问题发布了。