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