This is a bit of an academic exercise. I am implementing the sqrt function in Python. Here is my code,
def mySqrt(x):
low, high = 1, x
while low < high:
mid = low + (high - low)/2
if mid * mid > x:
high = mid - 1
elif mid * mid < x:
low = mid
else:
return mid
return low
The problem is that this does not work when the number is not a perfect square. I want to reverse engineer this function using log n complexity, which will return the sqrt value to the specified number of decimal places. So something like
def sqrt(num, param):
pass
In this way,
sqrt(5, 2) = 2.41
sqrt(5, 3) = 2.414
Can someone help me with this. Thank.
source
share