-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
117 lines (89 loc) · 2.65 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<title>Approximating Pi with the Stone in Pond Approach</title>
<link href='http://fonts.googleapis.com/css?family=Cinzel' rel='stylesheet' type='text/css'>
<style>
:root {
font-family: 'Cinzel', serif;
}
#inscribed_circle {
float: left;
border: 1px solid;
margin-right: 10px;
}
#display {
float: left;
font-size: 40px;
line-height: 40px;
width: 500px;
}
#result {
color: #dddddd;
}
#result #completed {
color: #000000;
}
</style>
<script>
var numberOfTries = 0,
numberInsideCircle = 0,
piString = Math.PI.toString();
var drawCircle = function() {
var centerX, centerY, radius;
window.canvas = document.getElementById('inscribed_circle');
window.context = canvas.getContext('2d');
centerX = radius = canvas.width / 2;
centerY = canvas.height / 2;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
context.stroke();
};
var insideCircle = function(coord) {
var absX = Math.abs(coord.x - 0.5),
absY = Math.abs(coord.y - 0.5),
distFromCenter = Math.sqrt(absX * absX + absY * absY);
return (distFromCenter <= 0.5);
};
var getApproximation = function() {
var value = (numberInsideCircle / numberOfTries) * 4,
approxString = value.toString(),
result = '<span id="completed">';
for ( var i = 0; i < approxString.length; i++ ) {
if (approxString[i] === piString[i]) {
result += approxString[i];
} else {
break;
}
}
result += '</span>';
result += approxString.slice(i);
return result;
};
var displayApproximation = function() {
document.getElementById('result');
document.getElementById('result').innerHTML = getApproximation();
};
var drawDot = function(coord, inside) {
context.fillStyle = inside ? '1b57e0' : '808080';
context.fillRect(Math.floor(coord.x * canvas.width), Math.floor(coord.y * canvas.height), 1, 1);
};
window.onload = function() {
drawCircle();
(function run() {
var sample = { 'x' : Math.random(), 'y' : Math.random() };
var inside = insideCircle(sample);
numberOfTries++;
if (inside) numberInsideCircle++;
drawDot(sample, inside);
displayApproximation();
setTimeout(run, 20);
}());
};
</script>
</head>
<body>
<canvas id='inscribed_circle' width='400' height='400'></canvas>
<div id='display' >Π ≈ <span id='result'></span></div>
</body>
</html>