python - 用于 N 维 ODE 系统的四阶 Runge-Kutta 积分器的索引列表超出范围错误
问题描述
问题参数:你构建的函数需要引入
- 自变量的当前值 (x)
- 因变量的当前值 (y) <-- (list)
- 自变量的步长 (h)
- 根据 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 )
解决方案
与 Matlab 不同,Python 在违反其边界时不会自动增加列表。利用
ym = n*[0.0]
等以初始化正确长度的列表。
或者只使用列表操作,则无需初始化
ym = [ y[i]+0.5*h*k1[i] for i in range(n) ]
或者
ym = [ yy+0.5*h*kk for yy,kk in zip(y,k1) ]
等等
此外,删除您不想离开函数的返回语句。
推荐阅读
- scikit-learn - scikit learn中的多目标岭回归如何工作?
- c++ - 代码组织
- git - GitHub 建议“强制推送可能会破坏您的拉取请求。” 为什么?
- javascript - 即使我的网站在 https 上,Pubnub Chat APi 也没有调用 SSL 请求
- java - java - 如何在java中的pdfbox中将文本放在矩形中?
- php - 安装 Laravel 时获取旧的 php 版本
- java - 无法使用 scim2 创建 askPassword 用户
- java - 如何设置变量imageview src?
- javascript - 如何在非 IE 浏览器(Chrome、Firefox、Edge)中的 Oracle APEX #orclapex 中获取 PC 名称(带/不带域)
- docker - Apk 添加 pdftk 不可满足的约束