** 运算符类型错误 [英] ** operator TypeError
本文介绍了** 运算符类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不断收到此错误消息:
I keep getting this error message:
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
是错误的类型,我假设它是字符串,为什么这是一个错误.
I don't understand why it's saying
that result**power
is of wrong type(s), I'm assuming it means string, and why that's an error.
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()
推荐答案
我认为你在这一行有一个错误:
I think you have a mistake on this line:
result = (x, power, epsilon)
我怀疑您想使用这三个值作为参数来调用 findroot
函数,而不是从中创建一个元组.尝试将其更改为:
I suspect you want to be calling the findroot
function with those three values as arguments rather than creating a tuple out of them. Try changing it to:
result = findroot(x, power, epsilon)
这篇关于** 运算符类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文