def findRoot(x, power, epsilon):
"""Assumes x and epsilon int or float, power an int,
epsilon > 0 & power >= 1
Returns float y such that y**power is within epsilon of x.
If such a float does not exist, it 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():
epsilon = 0.0001
for x in (0.25, -0.25):
for power in range(1, 4):
print 'Testing x = ' + str(x) +\
' and power = ' + str(power)
result = findRoot(x, power, epsilon)
if result == None:
print ' No root'
else:
print ' ', result**power, '~=', x
没有注释掉
if x < 0 and power%2 == 0:
return None
之前输出正常:
Testing x = 0.25 and power = 1
0.25 ~= 0.25
Testing x = 0.25 and power = 2
0.25 ~= 0.25
Testing x = 0.25 and power = 3
0.249907490797 ~= 0.25
Testing x = -0.25 and power = 1
-0.25 ~= -0.25
Testing x = -0.25 and power = 2
No root
Testing x = -0.25 and power = 3
-0.249907490797 ~= -0.25
注释掉以后到Testing x = -0.25 and power = 2下边就没往下走了,而且程序也没有退出然后出现shell提示符>>>,为什么这里不是继续输出0 ~= -0.25或其他呢?