Search code examples
mathpi

Accuracy of monte carlo simulation to calcualate π


I have created a website which uses a Monte Carlo simulation to calculate π, there are currently 3202959700000 'dots' and 2515023487209 are in the circle. Plugging this into the formula 4 * 2515023487209 / 3202959700000 returns 3.1408743446993728956377440527897 which is quite incorrect. Is this wrong since there just aren't enough 'dots' or did I just misplace them?


Solution

  • The code

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

    produces random coordinates in the range 0..499. This is not a uniform sampling of the interval 0..500, and thus one has to expect errors in the computation. One first fix is to add 0.5 to the coordinates so that the big square is subdivided into smaller squares that are represented by their centers. But in the end the accuracy of that method can not be better than counting the squares in the 500x500 subdivision that lie "mostly" inside the circle.