Lesson goal: The while-loop: solving equations

Previous: I'll guess your number | Home | Next: $\sqrt{n}-\sqrt{n-1}<0.01$

In a past lesson, a while loop was used to guess a number you were thinking of by bracketing in your guess, with tighter and tighter bounds, until your number was found. This was meant as an example of a while loop, and has a much more useful purpose: to solve equations in math.

Suppose you have a function $f(x)$ and you want to know for what $x$ is $f(x)=0$. For example, what about $f(x)=x^2+7x+10$, for what $x$ is $f(x)=0$? This is called "finding the roots" or "solving" the equation. Yes, we know, for $x^2+7x+10=0$ you could use the quadratic formula, but what would you do to solve $x+cos(5x^3)=0$?

In this lesson, we'll show you how to solve math equations using a while loop.

In order for this to work, you need to tell the computer two numbers, between which is the actual solution. Also, the sign of $f(x)$ must be different at $a$ and $b$. This is based on the premise that if a function changes sign between two numbers, it must pass through zero at some point in between. In other words, if the sign of $f(a)$ is opposite to the sign of $f(b)$, then we expect $f(x)$ to be zero at some point $x$ for $a\le x\le b$. If you can deliver the $a$ and $b$, then the following code will go and find your solution. It is known as the "bisection method" (ref).

Now you try. Try to put in an equation for $f(x)$ in the function f(x) return statement, and see if you can direct the program with your choices of $a$ and $b$ to find the roots of the equation.

Type your code here:

See your results here:

The code will run just fine..it's hard enough to understand this algorithm, so we didn't break it anywhere.

As far as learning about while-loops goes, see if you can understand the following:

  • The loop keeps going as long as variable stop is false.
  • The loop is told to stop if after bisections (i.e. $(a+b)/2$, no solution is found.
  • If $|f(x)|$ at some $x$ is $\le 0.001$ we assume this is close to zero and we've found a solution, so stop.
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.