Search code examples
pythonindexingerror-handlingpdediscretization

how to solve index out of bound in the discretization method in python


I'm trying to solve a PDE using discretization schemes the PDE in the form dudt=alphau+betadudx+gamma*d2udx2

*dudt the first derevative with respect to time

**dudx the first derevative with respect to space

***d2udx2 the secound derevative with respect to space

alpha,beta and gamma are defined

i tried the code down, but it gave an error "IndexError: index out of bounds " i don't know how to solve this problem, need some help here

Thanks in advance

import numpy as np
import matplotlib.pylab as plt


nx = 181
dx = np.pi / (nx - 1)
sigma = .03      
dt = sigma * dx  

R=6955e+5
eta=250e+6
nt=100
v0=11

lamda0=75*np.pi/180
x=np.linspace(0,np.pi,180)

u=np.sin(x)*np.cos(x)


for n in range(nt):
    un = u.copy()
    for i in range(1, nx-1):
        k=i*np.pi/180           
        lamda = np.pi-k
        if abs(lamda)<=lamda0:
            v=v0*np.sin(180*lamda/lamda0)
            v_prim=-v0*(np.cos(180*lamda/lamda0))   
        else:
            v=0
            v_prim=0

        alpha=v*np.cos(k)/np.sin(k)/R+v_prim/R
        beta=eta/R*np.cos(k)/np.sin(k)+v/R
        gamma=eta/R/R
        u[i] = un[i]*(1+alpha*dt) +(beta*dt/dx)*(un[i] - un[i-1]) + (gamma*dt/dx/dx) * (un[i+1] - 2 * un[i] + un[i-1])
        u[0] = un[0]*(1+alpha*dt) +(beta*dt/dx)*(un[0] - un[-1]) + (gamma*dt/dx/dx) * (un[1] - 2 * un[0] + un[-1])
        u[-1] = u[0]


plt.plot(x,u,label='B')
plt.legend()
plt.show()

Solution

  • u is an array of length 180. 0-179 are it's valid indexes. On the last iteration of your loop you are trying to access u[180] this is out of bounds as it doesn't exist.

    replacing

    for i in range(1, nx-1):
    

    with

    for i in range(1, nx-2):
    

    prevents this and the exception, but you should further examine your looping to ensure your algorithm is correct. Perhaps all of your calculations are shifted by 1 delta