11 res
= (res
>> 1) + bit
20 D
= num
# D is input (from num)
24 for i
in range(15, -1, -1): # negative ranges are weird...
28 R
= (R
<<2)|
((D
>>(i
+i
))&3)
29 R
= R
-((Q
<<2)|
1) #/*-Q01*/
33 R
= (R
<<2)|
((D
>>(i
+i
))&3)
34 R
= R
+((Q
<<2)|
3) #/*+Q11*/
37 Q
= (Q
<<1)|
1 #/*new Q:*/
39 Q
= (Q
<<1)|
0 #/*new Q:*/
47 def main(mantissa
, exponent
):
49 return Q(sqrt(mantissa
<< 1), # shift mantissa up
50 ((exponent
- 1) / 2)) # subtract 1 from exp to compensate
52 return Q(sqrt(mantissa
), # mantissa as-is
53 (exponent
/ 2)) # no compensating needed on exp
55 for Q
in range(1, int(1e7
)):
56 print(Q
, sqrt(Q
), sqrtsimple(Q
), int(Q
**0.5))
57 assert int(Q
**0.5) == sqrtsimple(Q
), "Q sqrtsimpl fail %d" % Q
58 assert int(Q
**0.5) == sqrt(Q
), "Q sqrt fail %d" % Q
60 //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
67 //Verilog function to find square root of a 32 bit number.
68 //The output is 16 bit.
70 input [31:0] num; //declare input
71 //intermediate signals.
74 reg [17:0] left,right,r;
77 //initialize all the variables.
81 left = 0; //input to adder/sub
82 right = 0; //input to adder/sub
84 //run the calculations for 16 iterations.
85 for(i=0;i<16;i=i+1) begin
86 right = {q,r[17],1'b1};
87 left = {r[15:0],a[31:30]};
88 a = {a[29:0],2'b00}; //left shift by 2 bits.
89 if (r[17] == 1) //add if r is negative
91 else //subtract if r is positive
95 sqrt = q; //final assignment of output.
97 endfunction //end of Function
100 c version (from paper linked from URL)
102 unsigned squart(D, r) /*Non-Restoring sqrt*/
103 unsigned D; /*D:32-bit unsigned integer to be square rooted */
106 unsigned Q = 0; /*Q:16-bit unsigned integer (root)*/
107 int R = 0; /*R:17-bit integer (remainder)*/
109 for (i = 15;i>=0;i--) /*for each root bit*/
113 R = R<<2)|((D>>(i+i))&3);
114 R = R-((Q<<2)|1); /*-Q01*/
118 R = R<<2)|((D>>(i+i))&3);
119 R = R+((Q<<2)|3); /*+Q11*/
121 if (R>=0) Q = Q<<1)|1; /*new Q:*/
122 else Q = Q<<1)|0; /*new Q:*/
125 /*remainder adjusting*/
126 if (R<0) R = R+((Q<<1)|1);
127 *r = R; /*return remainder*/
128 return(Q); /*return root*/
133 short isqrt(short num) {
135 short bit = 1 << 14; // The second-to-top bit is set: 1 << 30 for 32 bits
137 // "bit" starts at the highest power of four <= the argument.
142 if (num >= res + bit) {
144 res = (res >> 1) + bit;