Starting from:

$30

Math 152 – Python Lab 4

MATH 152 -
Python Lab
Math 152 – Python Lab 4
Directions: Use Python to solve each problem. (Template link)
1. Given the integral Z π/2
0
p4
5 + sin(x)dx
(a) Plot the function on the domain x ∈ [0, π/2].
(b) Recall the Left Endpoint Riemann Sum from MATH 151:
Z b
a
f(x)dx ≈
Xn
i=1
f(xi−1)∆x
where ∆x =
b − a
n
and xi = a + i · ∆x This is easy to compute in Python:
i. Define a list x from a (inclusive) to b (exclusive) with stepsize ∆x.
ii. Define a list y = f(x).
iii. Sum the list y and multiply by ∆x
Compute the Left Endpoint approximation using n = 200 subintervals.
2. The Right Endpoint Riemann Sum is the same process, but starting at a+ ∆x and ending
at b (inclusive).
Compute the Right Endpoint approximation using n = 200 subintervals.
3. The Midpoint Sum is again the same process, but starting at a +
∆x
2
and ending at b −
∆x
2
(inclusive).
(a) Compute the Midpoint approximation using n = 200 subintervals.
(b) Compute the average of the Left and Right Endpoint approximations. Is this equal to the
Midpoint approximation?
(More questions on page 2!!!!)
© 2022 TAMU Department of Mathematics MATH 152 Python Lab : Page 1 of 2
4. Another approximation for integrals is the Trapezoid Rule:
Z b
a
f(x)dx ≈
∆x
2
(f(x0) + 2f(x1) + 2f(x2) + . . . + 2f(xn−1) + f(xn))
There is a built-in function trapz in the package scipy.integrate (See the Overview for more
information).
(a) Compute the Trapezoid approximation using n = 200 subintervals.
(b) Is the Trapezoid approximation equal to the average of the Left and Right Endpoint
approximation?
(c) Run the following code to illustrate the trapezoid method with 4 trapezoids:
from numpy import ∗
import sympy a s sp
x=sp . symbols ( ’ x ’ )
f =(5+sp . s i n ( x ) ) ∗∗ sp . R a ti o n al ( 1 , 4 )
sp . pl o t ( f , ( x , 0 , pi / 2 ) )
xp =[0 , pi / 8 , pi / 4 , 3∗ pi / 8 , pi / 2]
yp=[ f . sub s ( x , i ) for i in xp ]
import m a t pl o tli b . p y pl o t a s p l t
p l t . pl o t ( xp , yp )
Notice that the trapezoid approximation is obtained by using lines to estimate f(x) on
each subinterval.
5. Simpson’s Method is another approximation to the integral which uses parabolas instead of
lines to approximate f(x):
Z b
a
f(x)dx ≈
∆x
3
(f(x0) + 2f(x1) + 4f(x2) + ... + 4f(xn−2) + 2f(xn−1) + f(xn))
(a) Use the function simps in the scipy.integrate package to compute Simpson’s Approximation using n = 200 subintervals.
6. The value of the integral to 10 decimal places is 2.4196410881. Use this value to estimate the
error |actual − estimate| in each of the five approximations.
© 2023 TAMU Department of Mathematics MATH 152 Python Lab : Page 2 of 2