为什么会出现这种TypeError?

时间:2014-09-28 12:05:17

标签: python python-2.7

我试图通过函数sqrt(a)找到平方根。 fixedPoint(f,epsilon)是一个辅助函数。问题是我遇到了这个TypeError:' float'对象不可调用。我是编程的新手,所以如果有人可以提供帮助并找到错误并解释这个错误意味着什么?

def fixedPoint(f, epsilon):
    """
    f: a function of one argument that returns a float
    epsilon: a small float

    returns the best guess when that guess is less than epsilon 
    away from f(guess) or after 100 trials, whichever comes first.
    """
    guess = 1.0
    for i in range(100):
        if abs(f(guess) - guess) < epsilon:
            return guess
        else:
            guess = f(guess)
    return guess


def sqrt(a):
    def tryit(x):
        return 0.5 * (a/x + x)
    return fixedPoint(tryit(a), 0.0001)

1 个答案:

答案 0 :(得分:4)

sqrt函数中,代码传递tryit的返回值(这是一个浮点值),而不是tryit本身。

传递函数本身将解决问题。

def sqrt(a):
    def tryit(x):
        return 0.5 * (a/x + x)
    return fixedPoint(tryit, 0.0001)