# hakanardo / sqrt / sqrt.py

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86``` ```def sqrt(y, n=10000): x = y / 2 while n > 0: #assert y > 0 and x > 0 #if y > 0 and x > 0: pass n -= 1 x = (x + y/x) / 2 return x def sqrt2(y, n=10000): a, b = 0, y while n > 0: n -= 1 c = (a + b) / 2 if c*c <= y: a = c if c*c >= y: b = c return c class Fix16(object): def __init__(self, val, scale=True): if isinstance(val, Fix16): self.val = val.val else: if scale: self.val = int(val * 2**16) else: self.val = val def __add__(self, other): return Fix16(self.val + Fix16(other).val, False) def __sub__(self, other): return Fix16(self.val - Fix16(other).val, False) def __mul__(self, other): return Fix16((self.val >> 8) * (Fix16(other).val >> 8), False) def __div__(self, other): return Fix16((self.val << 16) / Fix16(other).val, False) def __float__(self): return float(self.val) / float(2**16) def __int__(self): return self.val >> 16 def __cmp__(self, other): return cmp(self.val, Fix16(other).val) def __str__(self): return str(float(self)) __radd__ = __add__ __rmul__ = __mul__ def __rsub__(self, other): return Fix16(Fix16(other).val - self.val, False) def __rdiv__(self, other): return Fix16((Fix16(other).val << 16) / self.val, False) if __name__ == '__main__': #print sqrt(1234.0) print sqrt(1234) #print sqrt(1234.0, 100000000) #print sqrt(1234) #print sqrt(Fix16(1234)) #print sqrt(1234.0, 100000000) # pypy 0m1.209s # gcc 0m1.157s # cpython 0m28.713s #print sqrt(1234, 100000000) # pypy 0m6.278s # gcc 0m1.817s # cpython 0m22.246s #print sqrt(Fix16(1234), 100000000) # pypy 0m7.333s # gcc 0m1.885s # cpython 12m57.077s ```