首页 > 解决方案 > 在二分法中得到错误的输出

问题描述

我创建了以下执行二分法的代码。

我正在尝试使用它在区间 [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

标签: pythonbisection

解决方案


推荐阅读