Search code examples
javascriptmontecarlopi

Calculate pi using a Monte Carlo simulation


I've created this script

const size = 500;
const iterations = 10000000;

let inside = 0;
for (let i = 0; i < iterations; i++) {
  var Xpos = Math.floor(Math.random() * size);
  var Ypos = Math.floor(Math.random() * size);

  var dist = Math.hypot(Ypos-Xpos, size / 2 - size / 2);

  if (dist <= size / 2) {
    inside++;
  }
}

document.write(4 * inside / iterations);

see https://jsfiddle.net/tr8tnxdm/3/ which places 100000000 dots in a 500, 500 grid, the dots inside the circle get noted and in the end, it gets divided by the total and multiplied by 4.

This should output a very rough estimate of pi but it doesn't and I can't figure out why. I know that it isn't because of the below or equal to since I've also tried it with only below (line 11)


Solution

  • The problem is this line of code:

    var dist = Math.hypot(Ypos-Xpos, size / 2 - size / 2);
    

    One argument should be difference on one axis and another one should be difference on another axis, like this:

    var dist = Math.hypot(Xpos - size / 2, Ypos - size / 2);
    

    This change greatly improves an estimate (I'm getting 3.14...)