对分法中的错误输出

2024-04-26 17:40:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了下面的代码来执行二分法。你知道吗

我试图用它来寻找函数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

Tags: 函数代码answerinimportreturndefroot