Friday, August 15, 2014

Python: Use of recursive method to find the square root from scratch

Use of recursive method to find the square root from scratch

######################
### Recursive has a problem of bringing the results a bit less
def find_sqrt_2(x):
 ans  = 0
 diff1 = 0
 dec_ans = 0
 decimal_part = 0.0
 if x <= 0: return 0
 if x==1: return 1
 if x==2: return 1.414
 else:
  for i in range(1,x+1):
   t = i*i
   if t==x: 
    ans = i
    dec_ans = 0
    break
   elif t > x: 
    sqrt_int = i-1
    ans = sqrt_int
    tmp_sqr = sqrt_int*sqrt_int
    diff1 = x-tmp_sqr  
    ### Calculating the decimal part of the sqrt
    if diff1 >0:
     dec_ans = dec_ans + find_sqrt_2(diff1)
    break
 return ans+dec_ans/float(10)

No comments:

Post a Comment