Question

4. Another approximation for integrals is the Trapezoid Rule: integral (a to b)f(x) dx ≈ ∆x/2...

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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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

Add a comment
Know the answer?
Add Answer to:
4. Another approximation for integrals is the Trapezoid Rule: integral (a to b)f(x) dx ≈ ∆x/2...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT