Calculating PI with random numbers

Words
85
Reading
1 min
Listen
Play
9y

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

Calculating PI with random numbers | Ecency