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 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 and square[-1]: TypeError: 'float' object is not iterable
Anyone knows what can be wrong with the code?
Thanks in advance!
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 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
squarelist, to iterate both on
- iterate on
squareby elements on not its indices
ininstead 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, square[-1]): s1 += 0.01 * elt else: s2 += 0.01 * 0.5 * elt