索引超出范围

时间:2015-04-10 19:15:20

标签: python

我对Python比较陌生,所以我想这是一个简单的问题,但我真的没有看到解决方案。我正在尝试使用隐式中点规则来求解微分方程。但是我收到以下错误:

ifmp14@ifmp14:~/Desktop/progs/python/Serie 5$ python rk_Template.py
[ 0.  0.]
[  1.84457276e-06  -1.83923593e-06]
Traceback (most recent call last):
  File "rk_Template.py", line 135, in <module>
    y = IntegrateIM()
  File "rk_Template.py", line 129, in IntegrateIM
    y0[0] = fsolve(F, y0[0] + h* y0[1])
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py",  
  line 139, in fsolve
    res = _root_hybr(func, x0, args, jac=fprime, **options)
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 196, in _root_hybr
    shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
  File "/usr/lib/python2.7/dist-packages/scipy/optimize/minpack.py", line 19, in _check_func
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
  File "rk_Template.py", line 128, in <lambda>
    F = lambda x: y0[0] - x + h*rhs(0.5*(x+y0[0]),y0[1],x[i])
IndexError: index 1 is out of bounds for axis 0 with size 1

从我发现到目前为止,我得到了这个错误,因为Python获取的数组不是正确的大小,但我不明白为什么我会收到此错误。我还注意到第一次迭代有效,但第二次迭代中断了。

这是我的代码:

#Constants
V0 = 5 # Volt
f  = 50 # Hertz
n  = 1
Is = 1 * 10**(-9) #Ampere
Vt = 0.025 #Volt
R  = 100000 #Ohm
L  = 0.05 #Henry
C  = 10 * 10**(-9) # Farad

from numpy import *
from scipy.optimize import fsolve


def VIn(t):

    Vin = V0 * sin(2*pi*f*t)
    return Vin

def rhs(y1,y2,x):
    dy2dt = (Is*(exp((VIn(x)-(L*y1)/(n*Vt))-1)-(L/R)*y2-y1)*(1/(C*L)))
    return dy2dt

def IntegrateIM(y0=0.0,dy0=0.0,N=12001,tStart=0, tEnd = 30.0 * 10**(-3)):

    x = zeros(N+1)
    y0 = array([y0,dy0])
    #stepsize
    tEnd = float(tEnd)    
    h = ((tEnd - tStart)/N)

    y = zeros((N+1,2))
    y[0,:] = y0
    y[:,0] = dy0
    x[0] = tStart

    for i in range(0,N):
        print(y0)
        x[i+1] = x[i] + h
        tmp = y0[0]
        F = lambda x: y0[0] - x + h*rhs(0.5*(x+y0[0]),y0[1],x[i])
        y0[0] = fsolve(F, y0[0] + h* y0[1])
        y0[1] = y0[1] - h*rhs(0.5*(tmp + y0[0]),y0[1],x[i])
        y[i+1,:] = y0


    return y
y = IntegrateIM()

1 个答案:

答案 0 :(得分:0)

你正在重用x,它正在打破它:lambda F将x作为参数,但也已经使用了你的x数组。试试F = lambda z: y0[0] - z + h*rhs(0.5*(z+y0[0]),y0[1],x[i])