我不断收到此错误消息:

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'


我不明白为什么这样说
result**power类型错误,我假设它的意思是字符串,为什么会出现错误。

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()

最佳答案

我认为您在这条线上有一个错误:

result = (x, power, epsilon)


我怀疑您想使用这三个值作为参数来调用findroot函数,而不是根据它们创建一个元组。尝试将其更改为:

result = findroot(x, power, epsilon)

关于python - **运算符TypeError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38675717/

10-12 16:34