簡體   English   中英

IndexError:使用列表Python時列表索引超出范圍

[英]IndexError: list index out of range when using lists Python

朋友們好,我正在用python做數值方法、常微分方程的練習,你給了我一個列表索引超出范圍的錯誤,如果有人能幫我一把,我將不勝感激

import numpy as np
import matplotlib.pyplot as plt
 
def fun(x,y):
    return x**2/(1 +y**2)

"""#Runge-Kutta 1er orden
$y_(i+1)   =     y_i+  f(x_i,y_i )*h$
"""

def runge_kutta_1(f,a,b,h,y0): #función,inicial,final,tamaño de paso y y0
    x=[]
    y=[]
    x.append(a)
    y.append(y0)
    while x[0]<b:
        y.append(y[3]+f(x[0],y[3])*h)
        x.append(x[0] + h)
        return x,y

"""#Runge-Kutta 2do orden
$y_(i+1) = y_i+(1/3k1+2/3k2)*h$
"""

def runge_kutta_2(f,a,b,h,y0):
    x=[]
    y=[]
    x.append(a)
    y.append(y0)
    while x[0]<b:
        k1=f(x[0],y[3])
        k2=f(x[0]+3/4*h,y[3]+3/4*k1*h)
        y.append(y[3]+(1/3*k1+2/3*k2)*h)
        x.append(x[0]+h)
    return x,y

"""# Runge-Kutta 4to orden

$y_(i+1) =  y_i+1/6(k1+2k2+2k3+k4)*h$
"""

def runge_kutta_4(f,a,b,h,y0): 
    x=[]
    y=[]
    x.append(a)
    y.append(y0)
    while x[0]<b:
        k1=f(x[0],y[3])
        k2=f(x[0]+0.5*h,y[3]+0.5*k1*h)
        k3=f(x[0]+0.5*h,y[3]+0.5*k2*h)
        k4=f(x[0]+h,y[3]+k3*h)
        y.append(y[3]+(h/6)*(k1 +2*k2+2*k3+k4))
        x.append(x[0]+h)
    return x,y

h=0.5
print("tamaño de paso(0.5): ",h)
x1,y1=runge_kutta_1(fun,0,5,h,3)
x2,y2=runge_kutta_2(fun,0,5,h,3)
x4,y4=runge_kutta_4(fun,0,5,h,3)
x5=np.arange(0,5,0.01)
y5= y**3/3 + y - x**3/3                   #Solución analítica de la ED
 
# Gráfica
plt.figure(figsize=(15, 10), dpi=80) # Tamaño de la gráfica
plt.plot(x1,y1,label="RK 1er orden")
plt.plot(x2,y2,label="RK 2do orden")
plt.plot(x4,y4,label="RK 4to orden")
plt.plot(x5,y5,label="Solución Real")
plt.legend()
plt.show()

在第 58 行 x1,y1=runge_kutta_1(fun,0,5,h,3) *第 17 行中出現錯誤,在 runge_kutta_1 y.append(y +f(x,y) h) IndexError: list index out of range

您應該再次考慮索引順序。 您根據上一步中獲得的值計算下一步,因此您需要使用列表中的最后一個元素。 (使用局部變量避免重復訪問同一個數組元素。)

對於 RK2 方法,您的代碼需要更改為

def runge_kutta_2(f,a,b,h,y0):
    x=[a]
    y=[y0]
    while x[-1]<b:
        k1=f(x[-1],y[-1])
        k2=f(x[-1]+3/4*h,y[-1]+3/4*k1*h)
        y.append(y[-1]+(1/3*k1+2/3*k2)*h)
        x.append(x[-1]+h)
    return x,y

請務必考慮到x數組的最后一個元素很少等於或非常接近b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM