0

I've written a recursive binary search to calculate square roots with .001 precision. While my function arrives at the correct values, it does not return certain values.

def sqrtSearch(item, upper_bound, lower_bound = 0):
    midPoint = (upper_bound+lower_bound)/2
    if abs((midPoint)**2-item) <= .001:
        print(midPoint)
        return(midPoint)
    else:
        if (midPoint)**2-item > .001:
            sqrtSearch(item = item, upper_bound = midPoint, lower_bound =  lower_bound)
        else:
            sqrtSearch(item = item, upper_bound = upper_bound, lower_bound = midPoint)

x=4
rv = sqrtSearch(item=x, upper_bound = x)
print(rv)

x=9
rv = sqrtSearch(item=x, upper_bound = x)
print(rv)

What I have written returns:

2.0
2.0
3.000091552734375
None

But the "none" is unexpected. Why can I print this value but not return it?

Laura
  • 320
  • 1
  • 4
  • 12

1 Answers1

1

As mentioned in the comments you need return the result of your recursion.

def sqrtSearch(item, upper_bound, lower_bound = 0):
    midPoint = (upper_bound+lower_bound)/2
    if abs((midPoint)**2-item) <= .001:
        print(midPoint)
        return(midPoint)
    else:
        if (midPoint)**2-item > .001:
            return sqrtSearch(item = item, upper_bound = midPoint, lower_bound =  lower_bound)
        else:
            return sqrtSearch(item = item, upper_bound = upper_bound, lower_bound = midPoint)


x=4
rv = sqrtSearch(item=x, upper_bound = x)
print(rv)

x=9
rv = sqrtSearch(item=x, upper_bound = x)
print(rv)

now gives

2.0
2.0
3.000091552734375
3.000091552734375
modesitt
  • 7,052
  • 2
  • 34
  • 64