Python: Recursive function to calculate inverse power produces weird results

Viewed 325

I wrote two recursive functions(just to understand recursion) to calculate negative exponent of a number. The first one works perfectly but the 2nd one produces weird results for some cases. eg- power_recur(3,-1) produces .33 which is correct but power_recur(3,-2) it produces 1.

Also, for power_recur2(3,-2) if I change return 1/v to just return v, it returns 9. But when change it back to return 1/v it returns 1 instead of returning 1/9. I know I can make this work by just using the first function but I want to know why the 2nd function(power_recur2) isn't working?

This works:

def power_recur(x, exp):
    if exp < 0:
        exp = abs(exp)
        if exp == 0:
            z = 1
        else:
            z = x * power_recur(x, exp-1)
        return 1/z

    if exp == 0:
        return 1
    else:
        return x * power_recur(x, exp-1)

This doesn't work: (produces 1 for power_recur2(3,-2))

def power_recur2(x, exp):
    if exp < 0:
        if exp == 0:
            v = 1
        else:
            v = x * power_recur2(x, exp+1)
        return 1/v

    if exp == 0:
        return 1
    else:
        return x * power_recur2(x, exp-1)
1 Answers

The correct code is something like this.

def power_recur2(x, exp):
    if x == 0:
        return 0

    if exp < 0:
        return (1/x) * power_recur2(x, exp+1)

    if exp == 0:
        return 1
    else:
        return x * power_recur2(x, exp-1)

Good luck

Related