-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
112 lines (93 loc) · 3.29 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
<html>
<head>
<title>Happy π Day</title>
<style>
#estLine {
font-size: 18pt;
font-weight: bold;
}
#sq {
border: 1px solid black;
background: #d4d4d4;
width: 800px;
height: 800px;
position: relative;
}
div.point {
width: 3px;
height: 3px;
border: 0px;
position: absolute;
}
div.point.in {
background: red;
}
div.point.out {
background: white;
}
#greeting {
left: 324px;
top: 387px;
width: 151px;
height: 26px;
position: absolute;
font-size: 20pt;
z-index: 10;
}
</style>
</head>
<body>
<h1>Estimating π by Sampling a 2x2 square</h1>
Number of samples in Circle: <span id="ncirc">0</span><br>
Number of samples in Square but not Circle: <span id="nsq">0</span><br>
Pr(in Circle | in Square): <span id="pr"></span><br>
<span id="estLine">Estimated value of π: <span id="est"></span></span><br>
<div id="sq">
<span id="greeting">Happy π Day!</span>
</div>
<script>
const inCircle = (x, y) => {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) <= 1;
};
const ncircElem = document.getElementById("ncirc");
const nsqElem = document.getElementById("nsq");
const prElem = document.getElementById("pr");
const estElem = document.getElementById("est");
const sqElem = document.getElementById("sq");
var ncirc = 0;
var nsq = 0;
const doLoop = () => {
// Sample 2 x 2 square centered at origin
const x = Math.random() * 2 - 1;
const y = Math.random() * 2 - 1;
var inCirc = false;
// If in circle (ie dist from origin <= 1)
if (inCircle(x, y)) {
ncirc += 1;
inCirc = true;
}
nsq += 1;
// Update UI
ncircElem.textContent = ncirc;
nsqElem.textContent = nsq;
prElem.textContent = ncirc / nsq;
estElem.textContent = ncirc / nsq * 4;
var newPoint = document.createElement("div");
newPoint.className += " point";
if (inCirc) {
newPoint.className += " in";
} else {
newPoint.className += " out";
}
// NOTE: -1px because the box has width 2 and we want to
// center it on the point.
newPoint.style.left = (x + 1) / 2 * 800 - 1 + "px";
newPoint.style.top = (y + 1) / 2 * 800 - 1 + "px";
sqElem.appendChild(newPoint);
// Schedule to run again in 1/5 second
setTimeout(doLoop, 20);
};
doLoop();
</script>
</body>
</html>