Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the program in Python! We want to evaluate the integral integral_0^1 e^-t^

ID: 3837816 • Letter: W

Question

Write the program in Python!

We want to evaluate the integral integral_0^1 e^-t^2 dt. Write a Python (or C, etc.) function that computes this integral using the composite trapezoidal method with N subintervals of [0, 1]; here N is the input parameter of this function. We assume N lessthanorequalto 200. Hand in your program. Run this program and print the output when N has the values 10, 50, 100. Use the error formula of the composite trapezoidal method to find an upper bound on the error of this method for the above integral with N = 100.

Explanation / Answer

from math import exp
def trapezoidal(f, a, b, n):
h = float(b-a)/n
result = 0.5*f(a) + 0.5*f(b)
for i in range(1, n):
result += f(a + i*h)
result *= h
return result
  
def upperbound(U, a, b, n):
h = float(b-a)/n
result = 0
for i in range(1, n):
result += U(a + i*h)
result *= -(h**3/12)
return result
  
v = lambda t: exp((-t)**2)   
n = input('n: ')
n = int(n)
numerical = trapezoidal(v, 0, 1, n)
# Error formula to find an upper bound
U = lambda t: exp((-t)**2) * (4*(t**2) - 2) #double differentiation of function

uppererror = upperbound(v, 0, 1, n)

print('n=%d: numerical = %.16f, upper bound of error: %g' %(n, numerical, uppererror))

Output :

n=10: numerical = 1.4671746927387985, upper bound of error: -0.00106772

n=50: numerical = 1.4628329526162875, upper bound of error: -4.75217e-05

n=100: numerical = 1.4626970498492720, upper bound of error: -1.20342e-05