DEV Community

Discussion on: Calculating π with the Monte Carlo Simulation

Collapse
 
victorocna profile image
Victor Ocnarescu • Edited

What a great simulation and concept! I remember this from uni as well (not my uni, haha). One thing that I do not fully grasp is the concept of "inside". Can you please elaborate? A snippet from your code:

  for (let i = 0; i < dropCounter; i++) {
    const x = Math.random();
    const y = Math.random();
    const distance = Math.sqrt(x * x + y * y); // why sqrt?
    const isInside = distance < 1.0;
}
Enter fullscreen mode Exit fullscreen mode

PS: Here is a video of how Newton calculates PI. Spoiler: it involves a lot of math.

Collapse
 
zirkelc profile image
Chris Cook

Hi Victor,
thank you for your comment, I'm glad you like the simulation. You actually just spotted a mistake in my implementation. The sqrt() is wrong at this point. For a point to lie inside the quarter circle it must satisfy the condition of (x^2+y^2) < 1. When I implemented it a few months ago, I used a full circle instead of a quarter circle for visualisation. The full circle had a different point of center than (0, 0). So I originally used sqrt((x^2 - xc)+(y^2 -yc)) < 1 to check if it lies inside or outside (see this post for more information). Then I switched to a quarter circle with center at 0,0 and I forgot to change the formula accordingly.
Thank you for pointing that out - I changed it in the code as well!
P.S: I enjoyed your video! :)