]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/testsuite/gdc.test/runnable/pi.d
Add D front-end, libphobos library, and D2 testsuite.
[thirdparty/gcc.git] / gcc / testsuite / gdc.test / runnable / pi.d
1 // PERMUTE_ARGS:
2 // EXECUTE_ARGS: 1000
3
4 import core.stdc.stdio;
5 import core.stdc.time;
6
7 const int LONG_TIME=4000;
8
9 byte[] p;
10 byte[] t;
11 int q;
12
13 int main(char[][] args)
14 {
15 time_t startime, endtime;
16 int i;
17
18 if (args.length == 2) {
19 sscanf(&args[1][0],"%d",&q);
20 } else {
21 printf("Usage: pi [precision]\n");
22 return 1;
23 }
24
25 if (q < 0)
26 {
27 printf("Precision was too low, running with precision of 0.\n");
28 q = 0;
29 }
30
31 if (q > LONG_TIME)
32 {
33 printf("Be prepared to wait a while...\n");
34 }
35
36 // Compute one more digit than we display to compensate for rounding
37 q++;
38
39 p.length = q + 1;
40 t.length = q + 1;
41
42 /* compute pi */
43
44 time(&startime);
45 arctan(2);
46 arctan(3);
47 mul4();
48 time(&endtime);
49
50 // Return to the number of digits we want to display
51 q--;
52
53 /* print pi */
54
55 printf("pi = %d.",cast(int)(p[0]));
56 for (i = 1; i <= q; i++)
57 printf("%d",cast(int)(p[i]));
58 printf("\n");
59 printf("%lld seconds to compute pi with a precision of %d digits.\n", cast(long)(endtime-startime),q);
60
61 return 0;
62 }
63
64 void arctan(int s)
65 {
66 int n;
67
68 t[0] = 1;
69 div(s); /* t[] = 1/s */
70 add();
71 n = 1;
72 do {
73 mul(n);
74 div(s * s);
75 div(n += 2);
76 if (((n-1) / 2) % 2 == 0)
77 add();
78 else
79 sub();
80 } while (!tiszero());
81 }
82
83 void add()
84 {
85 int j;
86
87 for (j = q; j >= 0; j--)
88 {
89 if (t[j] + p[j] > 9) {
90 p[j] += t[j] - 10;
91 p[j-1] += 1;
92 } else
93 p[j] += t[j];
94 }
95 }
96
97 void sub()
98 {
99 int j;
100
101 for (j = q; j >= 0; j--)
102 if (p[j] < t[j]) {
103 p[j] -= t[j] - 10;
104 p[j-1] -= 1;
105 } else
106 p[j] -= t[j];
107 }
108
109 void mul(int multiplier)
110 {
111 int b;
112 int i;
113 int carry = 0, digit = 0;
114
115 for (i = q; i >= 0; i--) {
116 b = (t[i] * multiplier + carry);
117 digit = b % 10;
118 carry = b / 10;
119 t[i] = cast(byte)digit;
120 }
121 }
122
123 /* t[] /= l */
124
125 void div(int divisor)
126 {
127 int i, b;
128 int quotient, remainder = 0;
129
130 foreach (ref x; t)
131 {
132 b = (10 * remainder + x);
133 quotient = b / divisor;
134 remainder = b % divisor;
135 x = cast(byte)quotient;
136 }
137 }
138
139 void div4()
140 {
141 int i, c, d = 0;
142
143 for (i = 0; i <= q; i++) {
144 c = (10 * d + p[i]) / 4;
145 d = (10 * d + p[i]) % 4;
146 p[i] = cast(byte)c;
147 }
148 }
149
150 void mul4()
151 {
152 int i, c, d;
153
154 d = c = 0;
155
156 for (i = q; i >= 0; i--) {
157 d = (p[i] * 4 + c) % 10;
158 c = (p[i] * 4 + c) / 10;
159 p[i] = cast(byte)d;
160 }
161 }
162
163 int tiszero()
164 {
165 int k;
166
167 for (k = 0; k <= q; k++)
168 if (t[k] != 0)
169 return false;
170 return true;
171 }
172
173
174