#!/usr/bin/python
def find_close_int_sqrt_and_diff(x):
ans = 0
diff1 = 0
if x <= 0: return 0,0
# if x==1: return 1,0
# if x==2: return 1.414,0
else:
for i in range(1,x+1):
t = i*i
if t==x:
ans = i
diff1 = 0
break
elif t > x:
sqrt_int = i-1
ans = ans + sqrt_int
tmp_sqr = sqrt_int*sqrt_int
diff1 = x-tmp_sqr
break
return ans, diff1
############################################################################
k=249
l2, d = find_close_int_sqrt_and_diff(k)
while (d>0):
i, d = find_close_int_sqrt_and_diff(d)
l2 = l2+i/float(10)
print("the closest sqrt value of %d is %3.2f and the sqr is %3.2f" %(k, l2, l2*l2))
Friday, August 15, 2014
Python script to calculate an approximate square root - from scratch
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment