def findRoot1(x, power, epsilon):
low = 0
high = 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 findRoot2(x, power, epsilon):
if x < 0 and power % 2 == 0:
return None
#can't find even powered root of negative number
low = min(0, x)
high = max(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 findRoot3(x, power, epsilon):
"""x and epsilon int or float, power an int
epsilon > 0 and power >= 1
returns a float y s.t. 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
#can't find even powered root of negative number
low = min(-1, x)
high = max(1, 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
为什么 findRoot1(-27.0, 3, 0.001) 在第一种情况下会失败?逻辑是如何形成的?
为什么 findRoot2(0.25, 3, 0.001) 在第二种情况下会失败?findRoot2(-27.0, 3, 0.001) 如何通过这里?
它适用于第三种情况。如何?