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 a≤x≤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:
35
1
functionf(x)
2
return(x^2+7*x+10)
3
end
4
5
try=0
6
a=-10
7
b=-3
8
9
iff(a)*f(b)>0then
10
print("f(x) must have different signs at a and b.")
11
os.exit()
12
end
13
14
stop = false
15
whilestop == falsedo
16
x=(a+b)/2
17
ifmath.abs(f(x)) < 0.001then
18
stop = true
19
end
20
21
iff(a)*f(x) > 0then
22
a=x
23
else
24
b=x
25
end
26
x=(a+b)/2
27
print(x)
28
29
try=try+1
30
iftry > 100then
31
stop = true
32
end
33
34
end
35
print("solution is x=",x)
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 ≤0.001 we assume this is close to zero and we've found a solution, so stop.
Share your code
Show a friend, family member, or teacher what you've done!