n阶ODE的四阶Runge-Kutta积分器的索引列表超出范围误差

问题描述 投票:0回答:1

问题参数:您构建的功能需要接受自变量的当前值(x)因变量的当前值(y)

根据x和y计算导数的函数。

该函数将在x + h处返回因变量(y)的值

我们得到了一个测试人员代码,当我的运行时,我得到“列表索引超出范围”错误

我的代码是:

'''

def rk4( x, y, h, derivs ):
# ... Note, y is a list, ynew is a list, derivs returns a list of derivatives
n = len( y )
k1 = derivs( x, y )
ym = [ ]
ye = [ ]
slope = [ ]
ynew = [ ]

for i in range( n ):
    ym[ i ] = y[ i ] + k1[ i ] * h / 2 
    return ym

k2 = derivs( (x + h / 2), ym )

for i in range( n ):
    ym[ i ] = y[ i ] + k2[ i ] * h / 2
    return ym

k3 = derivs( (x + h / 2), ym )

for i in range( n ):
    ye.append( y[ i ] + k3[ i ] * h )
    return ye

k4 = derivs( (x + h), ye )

for i in range( n ):
    slope.append( (k1[ i ] + 2 * (k2[ i ] + k3[ i ]) + k4[ i ]) / 6 )
    ynew.append( y[ i ] + slope[ i ] * h )
    return ynew

x = x + h

return ynew

'''

测试人员代码:'''

if __name__ == '__main__':

# This is a spring/mass/damper system.
# The system oscillates and the oscillations should become smaller over time for positive stiffness and damping values
stiffness = 4;  #
damping = 0.5;


def derivs(t, y):
    return [y[1], -stiffness * y[0] - damping * y[1]]


y = [1, 4]
n = 50
tlow = 0
thigh = 10
h = (thigh - tlow) / (n - 1)
for ii in range ( n ):
    t = tlow + ii * h
    y = rk4 ( t, y, h, derivs )

'''

numerical-methods runge-kutta
1个回答
0
投票

Python,与Matlab相反,当违反边界时,不会自动增加列表。使用

y = n*[0.0]

初始化正确长度的列表。

也请在不希望离开该功能的地方删除return语句。

© www.soinside.com 2019 - 2024. All rights reserved.