gpt4 book ai didi

python - FindRootTest 不工作

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:44 25 4
gpt4 key购买 nike

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)

相反。

关于python - FindRootTest 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38679763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com