minor code-shuffle on sqrt() fn
[ieee754fpu.git] / src / add / fsqrt.py
1 from sfpy import Float32
2
3
4 # XXX DO NOT USE, fails on num=65536. wark-wark...
5 def sqrtsimple(num):
6 res = 0
7 bit = 1
8
9 while (bit < num):
10 bit <<= 2
11
12 while (bit != 0):
13 if (num >= res + bit):
14 num -= res + bit
15 res = (res >> 1) + bit
16 else:
17 res >>= 1
18 bit >>= 2
19
20 return res
21
22
23 def sqrt(num):
24 D = num # D is input (from num)
25 Q = 0
26 R = 0 # remainder
27 for i in range(64, -1, -1): # negative ranges are weird...
28
29 R = (R<<2)|((D>>(i+i))&3)
30
31 if R >= 0:
32 R -= ((Q<<2)|1) # -Q01
33 else:
34 R += ((Q<<2)|3) # +Q11
35
36 Q <<= 1
37 if R >= 0:
38 Q |= 1 # new Q
39
40 if R < 0:
41 R = R + ((Q<<1)|1)
42
43 return Q, R
44
45
46 # grabbed these from unit_test_single (convenience, this is just experimenting)
47
48 def get_mantissa(x):
49 return 0x7fffff & x
50
51 def get_exponent(x):
52 return ((x & 0x7f800000) >> 23) - 127
53
54 def set_exponent(x, e):
55 return (x & ~0x7f800000) | ((e+127) << 23)
56
57 def get_sign(x):
58 return ((x & 0x80000000) >> 31)
59
60 # convert FP32 to s/e/m
61 def create_fp32(s, e, m):
62 """ receive sign, exponent, mantissa, return FP32 """
63 return set_exponent((s << 31) | get_mantissa(m))
64
65 # convert s/e/m to FP32
66 def decode_fp32(x):
67 """ receive FP32, return sign, exponent, mantissa """
68 return get_sign(x), get_exponent(x), get_mantissa(x)
69
70
71 # main function, takes mantissa and exponent as separate arguments
72 # returns a tuple, sqrt'd mantissa, sqrt'd exponent
73
74 def main(mantissa, exponent):
75 if exponent & 1 != 0:
76 # shift mantissa up, subtract 1 from exp to compensate
77 mantissa <<= 1
78 exponent -= 1
79 m, r = sqrt(mantissa)
80 return m, r, exponent >> 1
81
82
83 def fsqrt_test(x):
84
85 xbits = x.bits
86 print ("x", x, type(x))
87 sq_test = x.sqrt()
88 print ("sqrt", sq_test)
89
90 print (xbits, type(xbits))
91 s, e, m = decode_fp32(xbits)
92 print("x decode", s, e, m, hex(m))
93
94 m |= 1<<23 # set top bit (the missing "1" from mantissa)
95 m <<= 27
96
97 sm, sr, se = main(m, e)
98 lowbits = sm & 0x3
99 sm >>= 2
100 sm = get_mantissa(sm)
101 #sm += 2
102 print("our sqrt", s, se, sm, hex(sm), bin(sm), "lowbits", lowbits,
103 "rem", hex(sr))
104 if lowbits >= 2:
105 print ("probably needs rounding (+1 on mantissa)")
106
107 sq_xbits = sq_test.bits
108 s, e, m = decode_fp32(sq_xbits)
109 print ("sf32 sqrt", s, e, m, hex(m), bin(m))
110 print ()
111
112 if __name__ == '__main__':
113
114 # quick test up to 1000 of two sqrt functions
115 for Q in range(1, int(1e4)):
116 print(Q, sqrt(Q), sqrtsimple(Q), int(Q**0.5))
117 assert int(Q**0.5) == sqrtsimple(Q), "Q sqrtsimpl fail %d" % Q
118 assert int(Q**0.5) == sqrt(Q)[0], "Q sqrt fail %d" % Q
119
120 # quick mantissa/exponent demo
121 for e in range(26):
122 for m in range(26):
123 ms, mr, es = main(m, e)
124 print("m:%d e:%d sqrt: m:%d-%d e:%d" % (m, e, ms, mr, es))
125
126 x = Float32(1234.123456789)
127 fsqrt_test(x)
128 x = Float32(32.1)
129 fsqrt_test(x)
130 x = Float32(16.0)
131 fsqrt_test(x)
132 x = Float32(8.0)
133 fsqrt_test(x)
134 x = Float32(8.5)
135 fsqrt_test(x)
136 x = Float32(3.14159265358979323)
137 fsqrt_test(x)
138 x = Float32(12.99392923123123)
139 fsqrt_test(x)
140 x = Float32(0.123456)
141 fsqrt_test(x)
142
143 """
144
145 Notes:
146 https://pdfs.semanticscholar.org/5060/4e9aff0e37089c4ab9a376c3f35761ffe28b.pdf
147
148 //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
149 //
150
151 module testbench;
152
153 reg [15:0] sqr;
154
155 //Verilog function to find square root of a 32 bit number.
156 //The output is 16 bit.
157 function [15:0] sqrt;
158 input [31:0] num; //declare input
159 //intermediate signals.
160 reg [31:0] a;
161 reg [15:0] q;
162 reg [17:0] left,right,r;
163 integer i;
164 begin
165 //initialize all the variables.
166 a = num;
167 q = 0;
168 i = 0;
169 left = 0; //input to adder/sub
170 right = 0; //input to adder/sub
171 r = 0; //remainder
172 //run the calculations for 16 iterations.
173 for(i=0;i<16;i=i+1) begin
174 right = {q,r[17],1'b1};
175 left = {r[15:0],a[31:30]};
176 a = {a[29:0],2'b00}; //left shift by 2 bits.
177 if (r[17] == 1) //add if r is negative
178 r = left + right;
179 else //subtract if r is positive
180 r = left - right;
181 q = {q[14:0],!r[17]};
182 end
183 sqrt = q; //final assignment of output.
184 end
185 endfunction //end of Function
186
187
188 c version (from paper linked from URL)
189
190 unsigned squart(D, r) /*Non-Restoring sqrt*/
191 unsigned D; /*D:32-bit unsigned integer to be square rooted */
192 int *r;
193 {
194 unsigned Q = 0; /*Q:16-bit unsigned integer (root)*/
195 int R = 0; /*R:17-bit integer (remainder)*/
196 int i;
197 for (i = 15;i>=0;i--) /*for each root bit*/
198 {
199 if (R>=0)
200 { /*new remainder:*/
201 R = R<<2)|((D>>(i+i))&3);
202 R = R-((Q<<2)|1); /*-Q01*/
203 }
204 else
205 { /*new remainder:*/
206 R = R<<2)|((D>>(i+i))&3);
207 R = R+((Q<<2)|3); /*+Q11*/
208 }
209 if (R>=0) Q = Q<<1)|1; /*new Q:*/
210 else Q = Q<<1)|0; /*new Q:*/
211 }
212
213 /*remainder adjusting*/
214 if (R<0) R = R+((Q<<1)|1);
215 *r = R; /*return remainder*/
216 return(Q); /*return root*/
217 }
218
219 From wikipedia page:
220
221 short isqrt(short num) {
222 short res = 0;
223 short bit = 1 << 14; // The second-to-top bit is set: 1 << 30 for 32 bits
224
225 // "bit" starts at the highest power of four <= the argument.
226 while (bit > num)
227 bit >>= 2;
228
229 while (bit != 0) {
230 if (num >= res + bit) {
231 num -= res + bit;
232 res = (res >> 1) + bit;
233 }
234 else
235 res >>= 1;
236 bit >>= 2;
237 }
238 return res;
239 }
240
241 """