How is the logic reasoning done in these three codes?

310 views Asked by At
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?

1

There are 1 answers

11
Anand S Kumar On BEST ANSWER

The issues in the cases are -

  1. First Case : You are assuming that the input you get x would always be positive , since you are always setting it to high, so when sending a negative number, ans in first iteration is -13.5 and since (-13.5)**3 is negative, it is always less than epsilon, hence you set -13.5 to low and 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.

  2. 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 on ans**power to be always greater than x , which would only work when x itself is greater than 1. Again, this causes low to be set to 0.125 after first iteration, and then it keeps on getting increased untill low becomes equal to high = 0.25 , in which case it enters infinite loop.

  3. Third Case : It works, because you changed the conditions of setting low and high such that ans is not less than 1 and it handles negative numbers as well.