我的对分法算法出了什么问题

时间:2018-10-05 16:37:43

标签: python python-3.x newtons-method

我正在做作业,我必须在python上锻炼平分法。在我看来,该算法看起来是正确的,但是当我运行代码时,我得到了

  

TypeError:*:'NoneType'和不支持的操作数类型   “ NoneType”

。 有什么问题,我该如何解决?

Q:表示多项式p(x)= a 0 + a 1 x + a 2 x 2 +⋯+ a n x n 作为系数列表[a 0 ,a 1 ,… ,a n ]。编写一个名为poly_critical的函数,该函数接受4个输入参数p,a,b和N,其中p是表示多项式p(x)的Python数字列表,a和b是定义区间[a,b]的数字,N是a正整数。

函数poly_critical实现应用于等式p'(x)= 0的二分法的N次迭代,并返回临界点c的近似值,其中c∈[a,b]的p'(c)= 0。

例如,如果p = [1,-1,1,0,0,1](代表p(x)= 1−x + x 2 + x 5 ),a = 0,b = 1和N = 10,然后该函数返回0.4212656546685004,其近似值为5x 4 + 2x-1 = 1 = 0。

poly_critical函数可以通过4种方式终止:

如果len(p) < 2(p为线性),则该功能应打印“无临界点”。并返回无。 如果任一初始端点都是关键点,请返回该端点。 如果端点和中点的值在任何迭代中都具有相同的符号,则该函数应打印“ Bisection方法失败”。并返回无。 该函数成功实现了对分方法的N次迭代,并返回第N个子间隔的中点。

我的算法:

def poly_critical(p,a,b,N):

    dp = [n*p[n] for n in range(1,len(p))]

    if len(p) < 2:
        print("No critical points")
        return None

    an = a
    bn = b

    def dP(x):

        seq = [dp[i]*x**i for i in range(1,len(dp))]
        sum_seq = sum(seq)
        return sum_seq

    if dP(an)*dP(bn) >= 0:
        print("Bisection method fails.")
        return None

    if dP(an)*dP(bn) < 0:
        mn = (an+bn)/2

        for n in range(1,N+1):
            mn = (an+bn)/2

            if dP(mn)*dP(an) < 0:
                an = an
                bn = mn

            elif dP(mn)*dP(bn) < 0:
                an = mn
                bn = bn

            elif dP(mn) == 0:
                return mn

            else:
                print("Bisection method fails.")
                return None

        return (an + bn)/2

0 个答案:

没有答案