FindRootTest不起作用

时间:2016-07-31 00:36:31

标签: python

File "/Users/SalamonCreamcheese/Documents/4.py", line 31, in <module>
    testFindRoot()
File "/Users/SalamonCreamcheese/Documents/4.py", line 29, in testFindRoot
    print " ", result**power, " ~= ", x
TypeError: unsupported operand type(s) for ** or pow(): 'tuple' and 'int'

任何帮助都会受到高度赞赏,我不明白为什么它说结果**的力量是类型的,我是假设意义字符串,为什么这是一个错误。提前感谢您的任何反馈。

def findRoot(x, power, epsilon):
    """Assumes x and epsilon int or float,power an int,
        epsilon > 0 and power >= 1
    Returns float y such that y**power is within epsilon of x
        If such a float does not exist, returns None"""
    if x < 0 and power % 2 == 0:
        return None
    low = min(-1.0, x)
    high = max(1,.0 ,x)
    ans = (high + low) / 2.0
    while abs(ans**power - x) > epsilon: 
        if ans**power < x:
            low = ans
        else:
            high = ans
        ans = (high +low) / 2.0
    return ans

def testFindRoot():
    for x in (0.25, -0.25, 2, -2, 8, -8):
        epsilon = 0.0001
        for power in range(1, 4):
            print 'Testing x = ' + str(x) +\
                  ' and power = ' + str(power)
            result = (x, power, epsilon)
            if result == None:
                print 'No result was found!'
            else:
                print " ", result**power, " ~= ", x

testFindRoot()

1 个答案:

答案 0 :(得分:5)

result = (x, power, epsilon)

result绑定到3元素元组。因此,错误消息非常准确,您稍后会尝试将该元组提升为整数幂power。 Python没有为元组定义__pow__,而这就是它的全部内容。

大概是打算代码:

 result = findRoot(x, power, epsilon)

代替。