Created the main function
[ieee754fpu.git] / src / add / fsqrt.py
index ba5fd60756109e009e586a09d37f9cefba58b3ba..c76267e7cc6b900d8cff941235dba02b37b1b9df 100644 (file)
@@ -1,5 +1,4 @@
-def sqrt(num):
-
+def sqrtsimple(num):
     res = 0
     bit = 1 << 14
 
@@ -11,11 +10,52 @@ def sqrt(num):
             num -= res + bit
             res = (res >> 1) + bit
         else:
-            res >>= 1;
-        bit >>= 2;
+            res >>= 1
+        bit >>= 2
 
     return res
 
+
+def sqrt(num):
+    D = num # D is input (from num)
+    Q = 0
+    R = 0
+    r = 0 # remainder
+    for i in range(15, -1, -1): # negative ranges are weird...
+
+        if (R>=0):
+        
+            R = (R<<2)|((D>>(i+i))&3)
+            R = R-((Q<<2)|1) #/*-Q01*/
+         
+        else:
+
+            R = (R<<2)|((D>>(i+i))&3)
+            R = R+((Q<<2)|3) #/*+Q11*/
+        
+        if (R>=0):
+            Q = (Q<<1)|1 #/*new Q:*/
+        else:
+            Q = (Q<<1)|0 #/*new Q:*/
+    
+
+    if (R<0):
+        R = R+((Q<<1)|1)
+        r = R
+    return Q
+
+def main(mantissa, exponent):
+    if exponent & 1 != 0:
+        return Q(sqrt(mantissa << 1), # shift mantissa up
+                ((exponent - 1) / 2)) # subtract 1 from exp to compensate
+    else:
+        return Q(sqrt(mantissa),      # mantissa as-is
+                (exponent / 2))       # no compensating needed on exp
+
+for Q in range(1, int(1e7)):
+    print(Q, sqrt(Q), sqrtsimple(Q), int(Q**0.5))
+    assert int(Q**0.5) == sqrtsimple(Q), "Q sqrtsimpl fail %d" % Q
+    assert int(Q**0.5) == sqrt(Q), "Q sqrt fail %d" % Q
 """
 //This is the main code of integer sqrt function found here:http://verilogcodes.blogspot.com/2017/11/a-verilog-function-for-finding-square-root.html
 //