2. Write a computer code to implement the Composite Trapezoidal Rule quadrature
ID: 3586862 • Letter: 2
Question
2. Write a computer code to implement the Composite Trapezoidal Rule quadrature to approximate the definite integral b, where using the equally spaced points zo = a, = xo + h, x,-zo + 2h, . .. ,.EN 11 = (b-a)/N (a) Test your code with f(x) = 1/(1+1)2 in [0,2] by computing the error l[f-Th[nl for h = 2/20, 2/40.2/80, and verify that T, has a convergent trend at the expected. quadratic rate. (b) Let f(x)-2/3 in [O, 1]. Compute T1/N for N = 16, 32, 64, 128, Do you see a second order convergence to the exact value of the integral? ExplainExplanation / Answer
def Trap(a, b, n, h):
area = (f(a) + f(b))/2.0
for i in xrange(1, n):
x = a + i*h;
area = area + f(x)
area = area*h
return area
# End of Trap
# Purpose: Compute value of function to be integrated
def f(x):
return_val = x*x + 1
return return_val
# End of f
# main function
print "Enter a, b, and n"
line = stdin.readline()
strings = line.split()
a = float(strings[0])
b = float(strings[1])
n = int(strings[2])
h = (b-a)/n
area = Trap(a, b, n, h)
print "With n =", n, "trapezoids, our estimate"
print "of the area from", a, "to", b, "= %.15f" % area
# End of main
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.