Processing math: 100%

Lesson goal: The while-loop: solving equations

Previous: I'll guess your number | Home | Next: nn1<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)=x2+7x+10, for what x is f(x)=0? This is called "finding the roots" or "solving" the equation. Yes, we know, for x2+7x+10=0 you could use the quadratic formula, but what would you do to solve x+cos(5x3)=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 axb. 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:

35
 
1
function f(x)
2
 return(x^2+7*x+10)
3
end
4
5
try=0
6
a=-10
7
b=-3
8
9
if f(a)*f(b)>0 then
10
 print("f(x) must have different signs at a and b.")
11
 os.exit()
12
end
13
14
stop = false
15
while stop == false do
16
 x=(a+b)/2
17
 if math.abs(f(x)) < 0.001 then
18
  stop = true
19
 end
20
 
21
 if f(a)*f(x) > 0 then
22
   a=x
23
 else
24
   b=x
25
 end
26
x=(a+b)/2
27
print(x)
28
29
try=try+1
30
if try > 100 then
31
   stop = true
32
 end
33
34
end
35
print("solution is x=",x)

See your results here: