Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Drop a bunch of needles
- var x1, y1, theta, x2, y2;
- for (var i = 0; i < numberToDrop; i++) {
- // Drop a new needle
- x1 = (Math.random() * (width - 2 * needleLength)) + needleLength;
- y1 = (Math.random() * (height - 2 * needleLength)) + needleLength;
- theta = Math.random() * 2 * Math.PI;
- x2 = x1 + needleLength * Math.cos(theta);
- y2 = y1 + needleLength * Math.sin(theta);
- // Check if it crosses a line
- // Yes, this isn't the best way to do this
- var crossesLine = false;
- for (var x = needleLength / 2; x <= canvas.width; x += needleLength) {
- if ((x1 <= x && x <= x2) || (x2 <= x && x <= x1))
- crossesLine = true;
- }
- // Record the toss
- tossed += 1;
- if (crossesLine) crossed += 1;
- }
- console.log("pi ~ " + (2 * tossed / crossed));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement