Calculating PI with random numbers

in #programming8 years ago (edited)

Also known as the Monte Carlo Method, a technique for solving problems with statistics.

The following will give you an approximation of Pi by generating x,y coordinate pairs and then determine how many of those that fall within a circle. From there with a bit of probability gives us our approximation of PI.

static double CalculatePi()
{
    var random = new Random();
    var inCircle = 0;
    int loopCount = 100000000;

    for (var i = 0; i < loopCount; i++)
    {
        var x = random.NextDouble();
        var y = random.NextDouble();
        if (((x * x) + (y * y)) <= 1)
        {
            inCircle++;
        }
    }

    var pi = 4.0m * inCircle / loopCount;
}

Here it is running. As you can see, not too far off. The more times you loop the closer it gets :)

NOTE: The PI symbol image is from Wikimedia Commons

Woz

Sort:  

Nice! I played around with a JavaScript implementation yesterday but I didn't write a post about it yet. I'm still trying to visualize the process by showing the random points on an actual circle and draw a live graph of the process. Maybe later this week :)

I'm all for \tau.

Btw. there is the math tag.

Your article has been upvoted and selected for Math-Trail Magazine N.14. You will also receive 5% of the author-rewards generated by the Magazine.