Evaluate integrals trapezoid rule using lists

I’m trying to write a formula for trapezoid rule from scratch. I’m not that familiar with python yet so I’m strugguling a bit. I have an expression I wish to integrate, which I wrote as a list called square.

I’m in the part of writing the integrals already:

square = []                        #Create empty list
for i in range(0, len(dos)):
     square.append(dos[i]*dist[i]) #Multiplication from inside the integral

s1 = 0
s2 = 0
for i in square[i] != square[1] and square[-1]:
    s1 += s1 + 0.01 * square[i]
else:
    s2 += s2 + 0.01 * 0.5 * square[i]
        
print(s1,s2)

And I am getting the following error:

for i in square[i] != square[1] and square[-1]:

TypeError: 'float' object is not iterable

Anyone knows what can be wrong with the code?

Thanks in advance!

Answer

You need the for loop and the if statement then, also you used += so you don’t need to add s1 in th right operand because that will add it twice

# equivalent
s1 += square[i]
s1 = s1 + square[i]
s1 = 0
s2 = 0
for i in range(len(square)):
    if square[i] != square[0] and square[i] != square[-1]:
        s1 += 0.01 * square[i]
    else:
        s2 += 0.01 * 0.5 * square[i]

With tome tips to get cleaner code

  • zip to create square list, to iterate both on dos and dist lists
  • iterate on square by elements on not its indices
  • use in instead of the double condition
square = [do * di for do, di in zip(dos, dist)]

s1 = 0
s2 = 0
for elt in square:
    if elt not in (square[0], square[-1]):
        s1 += 0.01 * elt
    else:
        s2 += 0.01 * 0.5 * elt