Skip to main content
 首页 » 编程设计

python之FindRootTest 不工作

2025年05月04日29zengkefu

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 is of type(s),我假设意思是字符串,为什么那是错误。提前感谢您的任何反馈。

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) 

result 绑定(bind)到 3 元素元组。所以错误消息是完全准确的,您稍后会尝试将该元组提升到整数幂 power。 Python 没有为元组定义 __pow__,仅此而已。

大概您打算编码:

 result = findRoot(x, power, epsilon) 

相反。