1
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
4

1 に答える 1

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

どうすればわかりますか?は1つしかなくreturn、関数の最後ではないためです。の場合、ループは終了し、その後には何もありません。そのため、関数はデフォルトで終了して戻りabs(evaluatePoly(poly, x)) >= epsilonます(明示的に返さない関数)。FalsewhileNonereturnNone

したがって、その状況での正しい戻り値を把握し、returnステートメントと関数の終わりを追加する必要があります。

于 2012-10-23T00:54:23.430 に答える