如何解决IndexError:列表赋值索引超出范围错误?

时间:2018-05-29 12:15:47

标签: python python-2.7

我使用ode方法编写了一个解码rk4的代码 这是代码:

from __future__ import division
import math
import numpy as np
from math import exp

def f(t,y):
  return 5*t**2-y/math.e**(t+y)
def rk4(t,y,h,i):
  p=[0]*i
  p[0] = y
  for n in range(0,i):
    g=11
    k1=round(h*f((t+n*h),y),g)
    k2=round(h*f((t+n*h)+(h/2),y+k1/2),g)
    k3=round(h*f((t+n*h)+h/2,y+k2/2),g)
    k4=round(h*f((t+n*h)+h,y+k3),g)
    p[n+1]=p[n]+(1/6)*(k1+2*k2+2*k3+k4)
    print(k1,k2,k3,k4)

a=rk4(0,1,0.1,3)
print(a)

当我尝试打印k的系数时,它显示列表分配索引超出范围错误,当我尝试打印p的值时,输出

[1, 0.9666652135433333, 0]

我不明白为什么第三项是0 我该如何解决这些问题?

1 个答案:

答案 0 :(得分:1)

我改进了您的代码段:

from __future__ import division
import math

def f(t, y):
    return 5 * t**2 - y/math.e**(t + y)

def rk4(t, y, h, i):
    p = list()
    p.append(y)
    for n in range(0, i):
        g = 11
        k1 = round(h * f((t + n * h), y), g)
        k2 = round(h * f((t + n * h) + (h/2), y + k1/2), g)
        k3 = round(h * f((t + n * h) + (h/2), y + k2/2), g)
        k4 = round(h * f((t + n * h) + h, y + k3), g)
        p.append(p[n] + (1/6) * (k1 + 2 * k2 + 2 * k3 + k4))
        print(k1, k2, k3, k4)

rk4(0, 1, 0.1, 3)

输出:

(-0.03678794412, -0.03373778195, -0.03373873966, -0.0282677314)
(-0.02828710837, -0.02041047991, -0.02041201684, -0.01011306051)
(-0.01011942119, 0.00259988829, 0.0025995445, 0.01774691262)