Designing a refinement loop for trapezoidal integration

Mark Yourself Question

  1. Grab a piece of paper and try this problem yourself.
  2. When you're done, check the "I have answered this question" box below.
  3. View the solution and report whether you got it right or wrong.

You need to approximate the integral of a smooth function f(x)f(x) over [a,b][a, b] by repeatedly refining the trapezoidal rule. Let tol be a positive threshold for agreement between successive estimates, not a guaranteed bound on the actual integration error. Assume n_max is an integer at least 4. Write Python code that:

  1. defines trap(f, a, b, n), which returns the trapezoidal-rule estimate with nn equal sub-intervals using an accumulation loop;
  2. defines integrate(f, a, b, tol, n_max), which starts with n=4n = 4, doubles nn for each permitted refinement, returns the estimate as soon as two successive estimates differ by less than tol, never uses more than n_max sub-intervals, and reports clearly when it stops without satisfying the agreement test.

Then explain, in two to four sentences, why the inner loop is a fixed-count for loop while the outer loop is condition-driven, and why the outer loop needs both stop conditions.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Applications of Loops Questions: