Skip to content

Instantly share code, notes, and snippets.

@louisjdcharles
Created July 22, 2019 15:11
Show Gist options
  • Save louisjdcharles/fc46c51ae08667b9116115acf3583cc0 to your computer and use it in GitHub Desktop.
Save louisjdcharles/fc46c51ae08667b9116115acf3583cc0 to your computer and use it in GitHub Desktop.
calculating-pi
<canvas width="500" height="500" id="gc"></canvas>
class point{
constructor(x, y){
this.x = x;
this.y = y;
}
}
window.setInterval(update, 10);
gc = document.getElementById("gc");
cc = gc.getContext('2d');
var pi;
var inside = 0;
var points = [];
function update(){
points.push(new point(Math.floor(Math.random() * 500), Math.floor(Math.random() * 500)));
cc.fillStyle = "#ffffff";
cc.fillRect(0, 0, gc.width, gc.height);
cc.fillStyle = "#000000";
// Begin Path
cc.beginPath();
// Arc Operation
cc.arc( 250, 250, 250, 0, Math.PI * 2, false );
// Fill Stroke
cc.stroke();
inside = 0;
for (var i = 0; i < points.length; i++){
if (Math.abs(Math.sqrt((points[i].x - 250) ** 2 + (points[i].y - 250) ** 2)) < 250){
cc.fillStyle = "#00ff00";
inside++;
}else{
cc.fillStyle = "#ff0000";
}
cc.fillRect(points[i].x, points[i].y, 3, 3);
}
pi = (inside / points.length) * 4;
console.log(pi);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment