UNPKG

1.91 kBHTMLView Raw
1<html>
2<head>
3 <title>Pi Machin</title>
4 <script src="../node_modules/decimal.js/decimal.js"></script>
5</head>
6<body>
7<script language="javascript">
8 Decimal.config({precision: 100});
9
10 // arctan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9 - ...
11 // = x - x^2*x^1/3 + x^2*x^3/5 - x^2*x^5/7 + x^2*x^7/9 - ...
12 function arctan(x) {
13 var y = x;
14 var yPrev = NaN;
15 var x2 = x.times(x);
16 var num = x;
17 var sign = -1;
18
19 for (var k = 3; !y.equals(yPrev); k += 2) {
20 num = num.times(x2);
21
22 yPrev = y;
23 y = (sign > 0) ? y.plus(num.div(k)) : y.minus(num.div(k));
24 sign = -sign;
25 }
26
27 return y;
28 }
29
30 function pi() {
31 // Machin: Pi / 4 = 4 * arctan(1 / 5) - arctan(1/239)
32 // http://milan.milanovic.org/math/english/pi/machin.html
33
34 // we calculate pi with a few decimal places extra to prevent round off issues
35 var DecimalPlus = Decimal.constructor({precision: Decimal.precision + 4});
36 var pi4th = new DecimalPlus(4).times(arctan(new DecimalPlus(1).div(5)))
37 .minus(arctan(new DecimalPlus(1).div(239)));
38
39 // the final pi has the requested number of decimals
40 return new Decimal(4).times(pi4th);
41 }
42
43 console.time('calculation');
44
45 var calculatedPi = pi();
46
47 console.timeEnd('calculation');
48
49 var mathematicaPi = '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664...';
50
51 document.write('<code>Calculated:&nbsp;&nbsp;' + calculatedPi + '</code><br>');
52 document.write('<code>Mathematica:&nbsp;' + mathematicaPi + '</code>');
53
54
55 /*
56 var mathematicaPi = '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664...';
57
58 document.write('<code>Calculated:&nbsp;&nbsp;' + pi + '</code><br>');
59 document.write('<code>Mathematica:&nbsp;' + mathematicaPi + '</code>');
60*/
61
62</script>
63</body>
64</html>
\No newline at end of file