在二等分法中得到错误的输出

时间:2018-11-06 00:27:09

标签: python bisection

我创建了以下代码,该代码可以执行二分法。

我正在尝试使用它来找到函数f(x)= x ^ 7-6x ^ 6-28x ^ 5 + 232x ^ 4-336x ^ 3-544x ^ 2 + 1728x-1152的根间隔[1,3.1]。

已提示我x_0 = 2是此间隔上此函数的根。我得到的是没有根,我希望有人可以帮助我解决这个问题!

下面是我的代码:

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")

这是我得到的输出:

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

0 个答案:

没有答案