3a8f8905680e5a94d52466a157239f1944dd63f5
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:*/
48 def main(mantissa
, exponent
):
50 return sqrt(mantissa
<< 1), # shift mantissa up
51 ((exponent
- 1) / 2) # subtract 1 from exp to compensate
52 return sqrt(mantissa
), # mantissa as-is
53 (exponent
/ 2) # no compensating needed on exp
56 if __name__
== '__main__':
57 for Q
in range(1, int(1e7
)):
58 print(Q
, sqrt(Q
), sqrtsimple(Q
), int(Q
**0.5))
59 assert int(Q
**0.5) == sqrtsimple(Q
), "Q sqrtsimpl fail %d" % Q
60 assert int(Q
**0.5) == sqrt(Q
), "Q sqrt fail %d" % Q
63 //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
70 //Verilog function to find square root of a 32 bit number.
71 //The output is 16 bit.
73 input [31:0] num; //declare input
74 //intermediate signals.
77 reg [17:0] left,right,r;
80 //initialize all the variables.
84 left = 0; //input to adder/sub
85 right = 0; //input to adder/sub
87 //run the calculations for 16 iterations.
88 for(i=0;i<16;i=i+1) begin
89 right = {q,r[17],1'b1};
90 left = {r[15:0],a[31:30]};
91 a = {a[29:0],2'b00}; //left shift by 2 bits.
92 if (r[17] == 1) //add if r is negative
94 else //subtract if r is positive
98 sqrt = q; //final assignment of output.
100 endfunction //end of Function
103 c version (from paper linked from URL)
105 unsigned squart(D, r) /*Non-Restoring sqrt*/
106 unsigned D; /*D:32-bit unsigned integer to be square rooted */
109 unsigned Q = 0; /*Q:16-bit unsigned integer (root)*/
110 int R = 0; /*R:17-bit integer (remainder)*/
112 for (i = 15;i>=0;i--) /*for each root bit*/
116 R = R<<2)|((D>>(i+i))&3);
117 R = R-((Q<<2)|1); /*-Q01*/
121 R = R<<2)|((D>>(i+i))&3);
122 R = R+((Q<<2)|3); /*+Q11*/
124 if (R>=0) Q = Q<<1)|1; /*new Q:*/
125 else Q = Q<<1)|0; /*new Q:*/
128 /*remainder adjusting*/
129 if (R<0) R = R+((Q<<1)|1);
130 *r = R; /*return remainder*/
131 return(Q); /*return root*/
136 short isqrt(short num) {
138 short bit = 1 << 14; // The second-to-top bit is set: 1 << 30 for 32 bits
140 // "bit" starts at the highest power of four <= the argument.
145 if (num >= res + bit) {
147 res = (res >> 1) + bit;