为什么我的牛顿方法函数返回None?

时间:2012-10-23 00:32:35

标签: python

def evaluatePoly(poly, x):
    '''
    Computes the value of a polynomial function at given value x. Returns that
    value as a float.

    poly: list of numbers, length > 0
    x: number
    returns: float
    '''
    for n in range(len(poly)):
        poly[n] = (poly[n]) * (x**n)

    return float(sum(poly[:]))

def computeDeriv(poly):
    '''
    Computes and returns the derivative of a polynomial function as a list of
    floats. If the derivative is 0, returns [0.0].

    poly: list of numbers, length > 0
    returns: list of numbers (floats)

    >>> print computeDeriv([-13.39, 0.0, 17.5, 3.0, 1.0])
    [0.0, 35.0, 9.0, 4.0]
    >>> print computeDeriv([6, 1, 3, 0])
    [1.0, 6.0, 0.0]
    >>> print computeDeriv([20])
    [0.0]

    '''
    if len(poly) == 1:
        poly = [0.0]
        return poly
    for m in range(len(poly)):
        poly[m] = float(m) * poly[m]
    return poly[1:]

def computeRoot(poly, x_0, epsilon):
    '''
    Uses Newton's method to find and return a root of a polynomial function.
    Returns a list containing the root and the number of iterations required
    to get to the root.

    poly: list of numbers, length > 1.
         Represents a polynomial function containing at least one real root.
         The derivative of this polynomial function at x_0 is not 0.
    x_0: float
    epsilon: float > 0
    returns: list [float, int]

    >>> print computeRoot([-13.39, 0.0, 17.5, 3.0, 1.0], 0.1,  .0001)
    [0.806790753796352, 7]
    >>> print computeRoot([1, 9, 8], -3, .01)
    [-1.0000079170005467, 5]
    >>> print computeRoot([1, -1, 1, -1], 2, .001)
    [1.0002210630197605, 4]
    '''
    x = x_0
    iter = 0
    list = []
    polyStart = poly[:]
    while abs(evaluatePoly(poly, x)) >= epsilon:
        poly = polyStart[:]
        l = evaluatePoly(poly,x)
        if abs(l) < epsilon:
            list.append(x)
            list.append(iter)
            return list
        else:
            poly = polyStart[:]
            d = computeDeriv(poly)
            dn = evaluatePoly(d, x)
            x = (x - (l/dn))
            iter = iter + 1

1 个答案:

答案 0 :(得分:0)

我认为你的意思是这个函数在某个特定的输入上返回None

def computeRoot(poly, x_0, epsilon):
    x = x_0
    iter = 0
    list = []
    polyStart = poly[:]
    while abs(evaluatePoly(poly, x)) >= epsilon:
        poly = polyStart[:]
        l = evaluatePoly(poly,x)
        if abs(l) < epsilon:
            list.append(x)
            list.append(iter)
            return list
        else:
            poly = polyStart[:]
            d = computeDeriv(poly)
            dn = evaluatePoly(d, x)
            x = (x - (l/dn))
            iter = iter + 1

我怎么知道?因为只有一个return,并且它不在函数的末尾。如果abs(evaluatePoly(poly, x)) >= epsilonFalse,则while循环将结束,之后没有任何内容,因此函数结束并默认返回None(任何不具有的功能)显式return返回None)。

因此,您需要确定在该情况下正确的返回值是什么,并添加return语句和函数的结尾。