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 # grabbed these from unit_test_single (convenience, this is just experimenting)
54 return ((x
& 0x7f800000) >> 23) - 127
56 def set_exponent(x
, e
):
57 return (x
& ~
0x7f800000) |
((e
+127) << 23)
60 return ((x
& 0x80000000) >> 31)
63 def main(mantissa
, exponent
):
65 return sqrt(mantissa
<< 1), # shift mantissa up
66 ((exponent
- 1) / 2) # subtract 1 from exp to compensate
67 return sqrt(mantissa
), # mantissa as-is
68 (exponent
/ 2) # no compensating needed on exp
71 if __name__
== '__main__':
72 for Q
in range(1, int(1e7
)):
73 print(Q
, sqrt(Q
), sqrtsimple(Q
), int(Q
**0.5))
74 assert int(Q
**0.5) == sqrtsimple(Q
), "Q sqrtsimpl fail %d" % Q
75 assert int(Q
**0.5) == sqrt(Q
), "Q sqrt fail %d" % Q
78 //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
85 //Verilog function to find square root of a 32 bit number.
86 //The output is 16 bit.
88 input [31:0] num; //declare input
89 //intermediate signals.
92 reg [17:0] left,right,r;
95 //initialize all the variables.
99 left = 0; //input to adder/sub
100 right = 0; //input to adder/sub
102 //run the calculations for 16 iterations.
103 for(i=0;i<16;i=i+1) begin
104 right = {q,r[17],1'b1};
105 left = {r[15:0],a[31:30]};
106 a = {a[29:0],2'b00}; //left shift by 2 bits.
107 if (r[17] == 1) //add if r is negative
109 else //subtract if r is positive
111 q = {q[14:0],!r[17]};
113 sqrt = q; //final assignment of output.
115 endfunction //end of Function
118 c version (from paper linked from URL)
120 unsigned squart(D, r) /*Non-Restoring sqrt*/
121 unsigned D; /*D:32-bit unsigned integer to be square rooted */
124 unsigned Q = 0; /*Q:16-bit unsigned integer (root)*/
125 int R = 0; /*R:17-bit integer (remainder)*/
127 for (i = 15;i>=0;i--) /*for each root bit*/
131 R = R<<2)|((D>>(i+i))&3);
132 R = R-((Q<<2)|1); /*-Q01*/
136 R = R<<2)|((D>>(i+i))&3);
137 R = R+((Q<<2)|3); /*+Q11*/
139 if (R>=0) Q = Q<<1)|1; /*new Q:*/
140 else Q = Q<<1)|0; /*new Q:*/
143 /*remainder adjusting*/
144 if (R<0) R = R+((Q<<1)|1);
145 *r = R; /*return remainder*/
146 return(Q); /*return root*/
151 short isqrt(short num) {
153 short bit = 1 << 14; // The second-to-top bit is set: 1 << 30 for 32 bits
155 // "bit" starts at the highest power of four <= the argument.
160 if (num >= res + bit) {
162 res = (res >> 1) + bit;