Write a function with the header function [integral, w] = myTrapRule(f, a, b, n)
ID: 3691420 • Letter: W
Question
Write a function with the header function [integral, w] = myTrapRule(f, a, b, n) which implements the trapezoidal rule for numerical integration. w is the rectangle width as determined by a, b, and n. Test Case 1: >> f1 = @(x) x.^5 + x.^3./sin(x).^4 + 1; >> [a,b] = myTrapRule(f1, 1, 2, 1000) a = 15.902027561738555 b = 1.000000000000000e-03 Test Case 2: >> f2 = @(bob) sin(bob).*cos(bob).*exp(bob).*tan(bob); >> [a,b] = myTrapRule(f2, 0, 5, 1000) a = 1.024075996301055e+02 b = 0.005000000000000
Explanation / Answer
def trapezoidal_rule(f, a, b, n): % we will be approximating the definite integral of f from a to b by the composite trapezoidal rule, using n subintervals h = (b - a) / n s = f(a) + f(b) for i in xrange(1, n): s += 2 * f(a + i * w) return s * w / 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.