0

I'm trying to find the trapezoidal integration of a bunch of data but it keeps saying

File "D:/uni work/Sci programming/aps3.py", line 25, in trapz
x2 = x[i+1]

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

I changed range(n) to range(n-1) but I still get the same error.

import numpy as np
solarfile = open('solar.dat','r',)
x1=[]#wavelength
y1=[]#irradiance
for theline in solarfile:
    num = theline.split()
    x1.append(float(num[0]))
    y1.append(float(num[1]))
x=np.array([x1])
y=np.array([y1])


a = int(input("Please Enter the lower bound: "))
b = int(input("Please enter the upper bound: "))
if (a<np.argmin(x)):
    a =np.argmin(x)
if (b>np.argmax(x)):
    b =np.argmax(x)
n = b - a
def trapz(x,y,a,b):
    traparray=[]
    for i in range(n-1):

        x1 = x[i]
        x2 = x[i+1]
        dx = x2-x1
        y1 = y[i]
        y2 = y[i+1] 
        dy = y2-y1
        trap = ((y1*dx)+(0.5*(dy*dx)))
        d = traparray.append(trap)
return (s)
print (trapz(x,y,a,b))
solarfile.close()

I keep trying things but they don't work.

wwii
  • 23,232
  • 7
  • 37
  • 77
  • You will need to put some logic in to ensure you don't ask for an item that doesn't exist. From the error message, it seems you are passing a sequence with only one item - there will never be a next item in that case. https://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python - may help. – wwii Feb 18 '20 at 23:18
  • What is the shape of `x`? - (`x.shape`) - Maybe `x=np.array([x1])` should be `x=np.array(x1)`? – wwii Feb 18 '20 at 23:22
  • i don't have intertools, my lecturer has only taught us numpy and matlibplot – The l3east 666 Feb 18 '20 at 23:23
  • Thanks for the help wwii, changing line 9 &10 fixed the error. now just to fix the actual for loop – The l3east 666 Feb 18 '20 at 23:26

1 Answers1

0

You're getting the index error since you're accessing an element in an array which doesn't exist.

Your n value is not defined, or it is also possible that it is using a global value of n, which is greater than the length of the array x.

Change your line on 25 to as below so that it only executes to the length of the array.

for i in range(len(x)-1)

AzyCrw4282
  • 7,222
  • 5
  • 19
  • 35
  • but n is the boundaries ' sorry should've included that in the code(b-a)' – The l3east 666 Feb 18 '20 at 23:17
  • I see. So what's happening is when you get to the final element you're trying to get the value of the next element, i.e. `x2 = x[i+1]` and this is not possible since it doesn't exist. So just change your for loop to `for i in range(n-2)` and it should work I think. – AzyCrw4282 Feb 18 '20 at 23:22