IndexError: index 10 is out of bounds for axis 0 with size 10

Tonikami04 picture Tonikami04 · Apr 8, 2016 · Viewed 49.7k times · Source

I am numerically setting up a mesh grid for the x-grid and x-vector and also time grid but again I have set up an array for x (position) which should only be between 0 and 20 and t (time) would be from 0 until 1000 thus in order to solve a Heat equation. But every time I want for e.g., I make the number of steps 10, I get an error:

"Traceback (most recent call last):
File "/home/universe/Desktop/Python/Heat_1.py", line 33, in <module>
x[i] = a + i*h
IndexError: index 10 is out of bounds for axis 0 with size 10"

Here is my code:

from math import sin,pi
import numpy
import numpy as np

#Constant variables
N = int(input("Number of intervals in x (<=20):"))
M = int(input("Number of time steps (<=1000):" ))

#Some initialised varibles
a = 0.0
b = 1.0
t_min = 0.0
t_max = 0.5

# Array Variables
x = np.linspace(a,b, M)
t = np.linspace(t_min, t_max, M) 


#Some scalar variables
n = []                         # the number of x-steps
i, s = [], []                  # The position and time

# Get the number of x-steps to use
for n in range(0,N):
    if n > 0 or n <= N:
         continue

# Get the number of time steps to use
for m in range(0,M):
    if m > 0 or n <= M:
         continue

# Set up x-grid  and x-vector
h =(b-a)/n
for i in range(0,N+1):
    x[i] = a + i*h

# Set up time-grid
k = (t_max - t_min)/m
for s in range(0, M+1):
    t[s] = t_min + k*s

print(x,t)

Answer

Mike M&#252;ller picture Mike Müller · Apr 8, 2016

You try to index outside the range:

for s in range(0, M+1):
    t[s] = t_min + k*s

Change to:

for s in range(M):
    t[s] = t_min + k*s

And it works.

You create t with length of M:

t = np.linspace(t_min, t_max, M) 

So you can only access M elements in t.

Python always starts indexing with zero. Therefore:

for s in range(M):

will do M loops, while:

for s in range(0, M+1):

will do M+1 loops.