<div id="title">Estimating Pi <br/>using the Monte Carlo Method</div>
<div id="stats">
<div>Total Inside Circle: <span id="total_inside_circle">0</span></div>
<div>Total Dots: <span id="total_dots">0</span></div>
<div>Estimated Value of PI: <span id="pi">-</span></div>
</div>
<canvas id="canvas" width="1000" height="1000"></canvas>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #feffe4;
font-family: Arial;
}
div#stats {
position: fixed;
top: 0px;
right: 0px;
text-align: right;
padding: 10px;
}
div#stats span {
font-weight: bold;
}
canvas {
display: block;
border: 1px solid #c2c2c2;
margin: 10vh auto;
background: #ffffff;
height: 80vh;
box-shadow: 3px 3px 3px 3px rgba(0, 0, 0, 0.31415);
}
#title {
position: fixed;
top: 0px;
left: 0px;
font-size: 27px;
color: rgba(0,0,0,0.31415);
padding: 10px;
font-weight: bold;
}
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const radius = canvas.width / 2;
const squareArea = canvas.width * canvas.height;
let insideCircle = 0;
let totalPoints = 0;
function calculatePi() {
if (totalPoints%10 == 0) {
const estimatedPi = (4 * insideCircle) / totalPoints;
total_inside_circle.innerHTML = insideCircle;
total_dots.innerHTML = totalPoints;
pi.innerHTML = estimatedPi.toFixed(8);
}
if(totalPoints == Number.MAX_SAFE_INTEGER) {
cancelAnimationFrame(animationId);
return;
}
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const distanceSquared = (x - radius) ** 2 + (y - radius) ** 2;
if (distanceSquared <= radius ** 2) {
insideCircle++;
ctx.fillStyle = 'green';
} else {
ctx.fillStyle = 'red';
}
ctx.beginPath();
ctx.arc(x, y, 3, 0, 2 * Math.PI);
ctx.fill();
totalPoints++;
animationId = requestAnimationFrame(calculatePi);
}
let animationId = requestAnimationFrame(calculatePi);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.