Skip to content

Instantly share code, notes, and snippets.

@coreygo
Last active January 25, 2016 01:29
Show Gist options
  • Save coreygo/5c5c9cc32b87319301d7 to your computer and use it in GitHub Desktop.
Save coreygo/5c5c9cc32b87319301d7 to your computer and use it in GitHub Desktop.
Monte-carlo
<div>π ≈ <span id="pi"></span><br /><canvas id='monte-carlo'></canvas></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.16/processing.min.js"></script>
<!-- <script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.21/p5.min.js"></script> -->
<script type="text/processing" data-processing-target="monte-carlo">
void setup() {
//Called initially
}
void draw() {
//Called in a loop, about 60 times per second
}
</script>
<script type="text/processing" data-processing-target="monte-carlo">
var inCircle = 0;
var inSquare = 0;
// each point, in turn, will be in this variable
var pt = 0;
//a function to see if a point is inside the circle:
var isInCircle = function(point) {
//check if the distance from the center of the circle the point is less than the radius
return Math.sqrt(Math.pow(101 - point.x,2) + Math.pow(101 - point.y, 2)) <= 100;
};
//a function to update the Pi approximation
var updateApprox = function() {
document.getElementById("pi").innerHTML = 4 * inCircle / inSquare;
};
void setup() {
//Make the frame rate as fast as possible (This might not be the best way to do it...)
frameRate(1000);
// set the size of the canvas
size(205,205);
// white background
background(255);
// set the fill on shapes to transparent
noFill();
// set the origin of the elipses to the upper right corner
ellipseMode(CORNER);
// set the thickness of the line
strokeWeight(2);
// set the line color to black
stroke(000);
// draw the square
rect(1,1,200,200);
// draw the inscribed circle
ellipse(1,1,200,200)
}
void draw () {
// generate a random point. Note: 'random' is a Processing function
pt = {x: random(1, 201), y: random(1, 201)};
// increment the correct counters, and change color depending on region
inSquare++;
stroke(0,255,0);
if(isInCircle(pt)) {
inCircle++;
stroke(255, 0, 0);
}
//draw the point
point(pt.x, pt.y);
//every 30 points, update the approximation
if(inCircle % 30 === 0) {
updateApprox();
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment