列表索引超出范围时出错

时间:2017-10-31 20:45:10

标签: python python-3.x

我知道,这是令人不舒服的代码,对不起。特别是,如果这是一个愚蠢的问题。

这是列表中的错误,我不知道为什么(我是初学者)。请有人告诉我,如何解决它?

这是输出:

Traceback (most recent call last):
  File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 77, in <module>
    vx, vy = rk3(diff1, 0, U0, 10, 100)
  File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 39, in rk3
    x,v=step(f, h, i, x0, U0)
  File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 11, in step
    k2 = f(x[i] + (1 / 3) * h[i], v[i] + (1 / 3) * k1)
IndexError: list index out of range

代码:

import matplotlib.pyplot as plt
import math as m
import pandas as pd

x =[0]*101
v =[0]*101

def step(f, h, i, x0, U0):
    x[0] = x0
    v[0] = U0
    k1 = f(x[i], v[i])
    k2 = f(x[i] + (1 / 3) * h[i], v[i] + (1 / 3) * k1)
    k3 = f(x[i] + (2 / 3) * h[i], v[i] + (2 / 3) * h[i] * k2)
    x[i] = x[i - 1] + h[i]
    v[i] = v[i - 1] + (h[i]) * ((1 / 4) * k1 + (3 / 4) * k3)
    return x, v


def rk3(f, x0, U0, x1, n):
    h = [(x1 - x0) / float(n)]
    for i in range(1, n+1):
        x,v=step(f, h, i, x0, U0)
        ###h= control(f, h[i], i, v[i], x0, U0)
    return x, v


def diff1(x, U):
    return 0.1


def diff(x, U):
    return -(m.cos(10 * x) + ((m.log(1 + x ** 2)) / (1 + x)) * (U ** 2) + U)


def exact_path():
    plt.grid()
    plt.plot(vx, vy)
    plt.show()


def table():
    mytable = pd.DataFrame({
        'Xn': vx,
        'Vn': vy,
    }, index=[i for i in range(0, 101)])
    mytable.index.name = 'number'
    pd.set_option('display.max_rows', None)
    print(mytable)


task = int(input("Task:"))
U0 = float(input("First value- U0:"))

if task == 2:
    vx, vy = rk3(diff, 0, U0, 10, 100)
    table()
    exact_path()

if task == 1:
    vx, vy = rk3(diff1, 0, U0, 10, 100)
    table()
    exact_path()

P.S。它是一个简单的3阶Runge-Kutta方法,但主要是synthax的问题​​。我试图用Python实现方法。

1 个答案:

答案 0 :(得分:0)

rk3()函数中,您h = [(x1 - x0) / float(n)]创建一个列表,其中只包含一个元素。这意味着可以与其一起使用的唯一有效非负索引将是h[0] - 并且尝试使用任何其他索引值,这可能在{{1}中的step()函数中}}循环,将导致for