I have created the following code which does the bisection method. I am trying to use it to find the root for the function $f(x)=x^7-6x^6-28x^5+232x^4-336x^3-544x^2+1728x-1152$ on the interval $[1, 3.1]$ I have been given a hint that $x_0 = 2$ is a root for this function on the interval. Heres my code below: I am getting that there is no root, I was hoping someone could help me fix this! thanks
import math
import numpy as np
def root(x):
return (x**7-6*x**6-28*x**5+232*x**4-336*x**3-544*x**2+1728*x-1152)
def bisection_method(f, a, b, tol):
if f(a)*f(b) > 0:
#end function, no root.
print("No root found.")
else:
iter = 0
while (b - a)/2.0 > tol:
midpoint = (a + b)/2.0
if f(a)*f(midpoint) < 0: # Increasing but below 0 case
b = midpoint
else:
a = midpoint
iter += 1
return(midpoint, iter)
answer, iterations = bisection_method(root, 1, 3.1, 10**(-14))
print("Answer:", answer, "\nfound in", iterations, "iterations")
This is the output I am getting:
No root found.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-ecdc56120415> in <module>()
21 return(midpoint, iter)
22
---> 23 answer, iterations = bisection_method(root, 1, 3.1, 10**(-14))
24 print("Answer:", answer, "\nfound in", iterations, "iterations")
TypeError: 'NoneType' object is not iterable
Bisection doesn't work when you have even-multiplicity roots (because $f$ has the same sign either side), which is the case here.
$$f(x)=(x - 2)^4 (x + 2) (x - 6) (x + 6)$$
Your program falls in the first test
if f(a)*f(b)>0: $f(1)=-105$ and $f(3.1)\approx -197$ so it immediately exit with no value returned.By the way,
iteris a Python built-in function returning an iterator object, so you shouldn't use it for a variable name.