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
Why does findRoot1(-27.0, 3, 0.001) fail in the first case? How is the logic made?
Why does findRoot2(0.25, 3, 0.001) fail in the second case? How findRoot2(-27.0, 3, 0.001) pass here?
It works everything for the third case. How?
The issues in the cases are -
First Case : You are assuming that the input you get
xwould always be positive , since you are always setting it to high, so when sending a negative number,ansin first iteration is -13.5 and since(-13.5)**3is negative, it is always less than epsilon, hence you set -13.5 tolowand from there on it keeps decreasing (goes to -20.25 in the next iteration) till it reaches -27 (that is when low and high both become -27) and then it goes into infinite loop.Second Case : You are not handling the case where the number is less than 1 , in such case, power of that number would be lesser , for example ,
x = 0.125,x^3 = 0.001953125. But your logic for second case depends onans**powerto be always greater thanx, which would only work whenxitself is greater than 1. Again, this causeslowto be set to0.125after first iteration, and then it keeps on getting increased untilllowbecomes equal tohigh=0.25, in which case it enters infinite loop.Third Case : It works, because you changed the conditions of setting
lowandhighsuch thatansis not less than 1 and it handles negative numbers as well.