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