Lesson goal: Doing integrals numerically

Previous: Testing the derivative | Home | Next: Introduction

You might remember integration from calculus as being interpreted as the "area under the curve." This is a true, albiet short-sighted idea, but we'll go with it here. You may have learned to do definite integrals like $\int_0^1 x^2 dx=\frac{1}{3}x^3|_0^3$. This would be simplified to $\frac{1}{3}[1^3-0^3]=0.333$.

In this lesson, we'll learn how to have the computer do such integrals for us. The integrals we'll do here are definite integrals (with upper and lower limits), and with the typical functions found in a first-term calculus class.

The plan here is one found in your elementary calculus book: panel a bunch of small rectangles under the curve-to-integrate, find the area of each rectangle, add up the areas of all of these rectanlges, and this will be our total "area under the curve" (and answer to your integral).

Now you try. Fix the function $f(x)$ to return the function you wish to integrate. Then, fix the N= line to reflect the number of rectanges you want under your curve. Next fix the upper and lower limits, $a$ and $b$. Lastly, the sum=sum+ line to add the area of the current rectangle to the running sum of areas.

Type your code here:


See your results here:

This code will not run! You have to make these fixes first:
  • Fix the function $f(x)$ to return the function you wish to integrate.
  • Fix the N= line to reflect the number of rectanges you want under your curve.
  • Next fix the upper and lower limits of your integral, $a$ and $b$.
  • Fix the sum=sum+ line to add the area of the current rectangle to the running sum of areas.
Make sure this all works. Pick an integral, say like $\int_0^{10} x dx$. What do you get when you do it by hand? The program here should give you the same result. The power here is when the computer can give you the answer to an integral that you cannot do by hand. How about this one? $\int_0^\pi x^2 cos(1/x)^2 dx$ (we got 8.13 for the answer)?

Also, the value of the $N$ (the number of rectangles to be tiled under your function), is very important to this program. What effects does it have on your answers? Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.