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