85051e086eb1f105816b2b5fd49b3d3fd69aa018
[ieee754fpu.git] / src / add / fsqrt.py
1 def sqrt(num):
2
3 res = 0
4 bit = 1 << 14
5
6 while (bit > num):
7 bit >>= 2
8
9 while (bit != 0):
10 if (num >= res + bit):
11 num -= res + bit
12 res = (res >> 1) + bit
13
14 else:
15 res >>= 1;
16 bit >>= 2;
17
18 return res
19
20 """
21 //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
22 //
23
24 module testbench;
25
26 reg [15:0] sqr;
27
28 //Verilog function to find square root of a 32 bit number.
29 //The output is 16 bit.
30 function [15:0] sqrt;
31 input [31:0] num; //declare input
32 //intermediate signals.
33 reg [31:0] a;
34 reg [15:0] q;
35 reg [17:0] left,right,r;
36 integer i;
37 begin
38 //initialize all the variables.
39 a = num;
40 q = 0;
41 i = 0;
42 left = 0; //input to adder/sub
43 right = 0; //input to adder/sub
44 r = 0; //remainder
45 //run the calculations for 16 iterations.
46 for(i=0;i<16;i=i+1) begin
47 right = {q,r[17],1'b1};
48 left = {r[15:0],a[31:30]};
49 a = {a[29:0],2'b00}; //left shift by 2 bits.
50 if (r[17] == 1) //add if r is negative
51 r = left + right;
52 else //subtract if r is positive
53 r = left - right;
54 q = {q[14:0],!r[17]};
55 end
56 sqrt = q; //final assignment of output.
57 end
58 endfunction //end of Function
59
60
61 c version (from paper linked from URL)
62
63 unsigned squart(D, r) /*Non-Restoring sqrt*/
64 unsigned D; /*D:32-bit unsigned integer to be square rooted */
65 int *r;
66 {
67 unsigned Q = 0; /*Q:16-bit unsigned integer (root)*/
68 int R = 0; /*R:17-bit integer (remainder)*/
69 int i;
70 for (i = 15;i>=0;i--) /*for each root bit*/
71 {
72 if (R>=0)
73 { /*new remainder:*/
74 R = R<<2)|((D>>(i+i))&3);
75 R = R-((Q<<2)|1); /*-Q01*/
76 }
77 else
78 { /*new remainder:*/
79 R = R<<2)|((D>>(i+i))&3);
80 R = R+((Q<<2)|3); /*+Q11*/
81 }
82 if (R>=0) Q = Q<<1)|1; /*new Q:*/
83 else Q = Q<<1)|0; /*new Q:*/
84 }
85
86 /*remainder adjusting*/
87 if (R<0) R = R+((Q<<1)|1);
88 *r = R; /*return remainder*/
89 return(Q); /*return root*/
90 }
91
92 From wikipedia page:
93
94 short isqrt(short num) {
95 short res = 0;
96 short bit = 1 << 14; // The second-to-top bit is set: 1 << 30 for 32 bits
97
98 // "bit" starts at the highest power of four <= the argument.
99 while (bit > num)
100 bit >>= 2;
101
102 while (bit != 0) {
103 if (num >= res + bit) {
104 num -= res + bit;
105 res = (res >> 1) + bit;
106 }
107 else
108 res >>= 1;
109 bit >>= 2;
110 }
111 return res;
112 }
113
114 """