A Pen by louisjdcharles on CodePen.
Created
July 22, 2019 15:11
-
-
Save louisjdcharles/fc46c51ae08667b9116115acf3583cc0 to your computer and use it in GitHub Desktop.
calculating-pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<canvas width="500" height="500" id="gc"></canvas> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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