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