Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. // Drop a bunch of needles
  2. var x1, y1, theta, x2, y2;
  3. for (var i = 0; i < numberToDrop; i++) {
  4. // Drop a new needle
  5. x1 = (Math.random() * (width - 2 * needleLength)) + needleLength;
  6. y1 = (Math.random() * (height - 2 * needleLength)) + needleLength;
  7. theta = Math.random() * 2 * Math.PI;
  8.  
  9. x2 = x1 + needleLength * Math.cos(theta);
  10. y2 = y1 + needleLength * Math.sin(theta);
  11.  
  12. // Check if it crosses a line
  13. // Yes, this isn't the best way to do this
  14. var crossesLine = false;
  15. for (var x = needleLength / 2; x <= canvas.width; x += needleLength) {
  16. if ((x1 <= x && x <= x2) || (x2 <= x && x <= x1))
  17. crossesLine = true;
  18. }
  19.  
  20. // Record the toss
  21. tossed += 1;
  22. if (crossesLine) crossed += 1;
  23. }
  24.  
  25. console.log("pi ~ " + (2 * tossed / crossed));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement