FindRootTest不起作用

jac*_*k.b 1 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'
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

Tim*_*ers 5

result = (x, power, epsilon)
Run Code Online (Sandbox Code Playgroud)

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

大概你打算编码:

 result = findRoot(x, power, epsilon)
Run Code Online (Sandbox Code Playgroud)

代替.