I was asked to find the root of an equation using the Bisection method and only for
loops with Python 3. This thread shows how to use the method, but not with the explanation for the number in range()
.
As an example, I have the function
f(x) = x2 - 2*x - 3
and I want to find its negative root, starting with the interval [-4, 1].
I managed to write the function with a for
loop, but I don't understand which range I should use, or how to come up with it.
Here is my code, that solves the problem:
...
a = -4
b = 1
c = (a + b)/2
for i in range(1000):
if f(c) == 0:
break
if f(a) * f(c) < 0:
b = c
elif f(a) * f(c) > 0:
a = c
c = (a + b) / 2
return c, f(c), i
c = -1 (found the negative root), f(c) = 0 confirming that the program works, and i = 52 which indicates that after 52 "tries" of bisection, it found the right answer.
I put a very large number in range()
to make sure I found the root, but why does it need only 52 iterations?
Plus, if my interval changed to [-2, 1], I would need 53 tries. Why is that so?