4. Another approximation for integrals is the Trapezoid Rule:
integral (a to b)f(x) dx ≈ ∆x/2 (f(x_0) + 2f(x_1) + 2f(x_2) + · · · + 2f(x_n−2) + 2f(x_(n−1)) + f(x_n))
There is a built-in function trapz in the package scipy.integrate (refer to the Overview for importing and using this and the next command).
(a) Compute the Trapezoid approximation using n = 100 subintervals.
(b) Is the Trapezoid approximation equal to the average of the Left and Right Endpoint approximations? (c) Run the following code to illustrate the trapezoid method with 4 trapezoids (make sure you imported sympy as sp as stated in the Overview):
• x=sp.symbols(’x’)
• f=sp.exp(x/2)/x**3
• sp.plot(f,(x,1,5))
• xp=[1,2,3,4,5]
• yp=[f.subs({x:i}) for i in xp]
• import matplotlib.pyplot as plt
• plt.plot(xp,yp) Notice that the trapezoid approximation is obtained by using lines to estimate f(x) on each subinterval.
Code
import math import matplotlib.pyplot as plt import numpy as np def trapz(): a = 1 b = 5 N = 100 h = (b - a) / N x = np.linspace(a, b, N) f = lambda x: math.exp(x / 2) / x ** 3 y = [] summation = 0 for i in range(len(x)): x_val = f(x[i - 1]) + f(x[i]) summation = summation + x_val * h * 0.5 y.append(summation) print(summation) plt.plot(x, y) plt.show() trapz()
# please comment in case of any query
Output
4. Another approximation for integrals is the Trapezoid Rule: integral (a to b)f(x) dx ≈ ∆x/2...
Problem 3. Suppose you are programming the composite trapezoid rule (CTR) to approximate 1(f) =| f(x) dx using the TR with N subintervals, and that you mistakenly forget to weight down the two endpoints by 3. That is, you have accidentally programmed the quadrature rule where h-%.. (Note: sinoefe C, you know that UIL is bounded.) 1. Find QBADN -OCTRN where QCTRN ) is the approximation to (x) dx computed via the CTR with N subintervals. Problem 3. Suppose you...
10. Trapezoidal Rule is used to approximate the integral f(a) dx using 1- (yo +2y1 + 2y2 + x-na b-a + 2yn-1 +%),where Use this approximation technique to estimate the area under the curve y = sinx over。 a. π with n 4 partitions. x A 0 B: @ Δy B-A b. The error formula for the trapezoidal rule is RSL (12ba)1 where cischosen on the interval [a, b] to maximize lf" (c)l. Use this to compute the error bound...