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