Question about writing out a trapezoidal integration method
Hi I am currently writing a Python program that divide 1
to 0
to n
pieces, and integrate it base on number of pieces, each trapezoid will have (10)/n
as their equal width.
Here is the code:
from numpy import sqrt,sin,arange
def f(x):
return (sin(sqrt(100*x))**2)
def trapezoidal(f, a, b, n):
h = float(b  a) / n
s = 0.0
s += f(a)/2.0
for i in range(1, n):
s += f(a + i*h)
s += f(b)/2.0
return s * h
print(trapezoidal(f(x), 5, 10, 100))
Do you guys think this code could work ?Also, how do you add a sequence or a loop that it calculate area for 1,2,4,8,16
until 2^10
?
1 answer

incorrect indentation. try this
import numpy as np def f(x): return (np.sin(np.sqrt(100*x))**2) def trapezoidal(f, a, b, n): h = float(b  a) / n s = 0.0 s += f(a)/2.0 for i in range(1, n): s += f(a + i*h) s += f(b)/2.0 return s * h print( trapezoidal(f(x), 5, 10, 100))