2016-07-30 60 views
1

我不斷收到此錯誤信息:**操作類型錯誤

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

顯然你不知道「類型」只是「類型或類型」的簡稱。 –

回答

2

我覺得你在這一行錯誤:

result = (x, power, epsilon) 

我懷疑你想被調用findroot函數與三個值作爲參數而不是從它們中創建一個元組。嘗試將其更改爲:

result = findroot(x, power, epsilon) 
1

你不能對一個元組應用一個powers操作。如果您需要具備所有這些能力值,請嘗試單獨操作。

您可能需要: [功率** N對結果N]

2

result**power正在試圖尋找x to the y其中x = resulty = power。您的問題是result元組。你不能提高元組的權力。這是沒有意義的......

你需要訪問應該被取冪和指數的元組內的值。

例如,result[0] ** powerresult[1] ** power

2

它看起來像你的意思是叫findRoot與三個參數xpowerepsilon。嘗試編輯行

result = (x, power, epsilon) 

result = findRoot(x, power, epsilon) 

由於該行目前就是result不是數字(你會想爲**運營商)。 result一個元組中有三個不同的對象:xpowerepsilon。您可以在result中的任意兩個項目上使用**運算符,但對於tuple類型沒有定義它。

相關問題