How to calculate π (PI) using monte carlo method with C#.

mohamadhag

Mohamad Hag

Posted on August 27, 2021

How to calculate π (PI) using monte carlo method with C#.

Overview

π is a mathematical constant number, approximately equal to 3.14159. It represents the ratio of a circle's circumference to its diameter. So, how they calculated this magical number 😀. Actually, there are a lot of methods to calculate it; one of the most famous methods is monte carlo. In this post I'll try to explain how this can be done mathematically then programmatically using C#.

Finding the π formula

We know that the area of the circle is:
A = π(R^2) Where R is the radius of the circle.

After isolating π the formula should be:
π = A / (R^2) ... (1)

The area of the circle quarter is:
Q = A / 4

Then the area should be:
A = 4 * Q ... (2)

Let's change A in (1) formula to (4 * Q) in (2) formula, the result should be:
π = (4 * Q) / (R^2)

Check the figure below, and read the following lines:
Q here can be denoted as number of points taken in the circle area (only red area). while R^2 is the number of points on the whole square area (red and blue areas).
Alt Text
Thus, the the final equation is:
π = (4 * M) / (N)
Where:
M is the number of points on the circle.
N is the number of points on the square.

Implementing the result with CSharp:

Let's create a new CSharp console application to get started.

First, I created a simple class to help storing point structure (X, Y) as following:

using System;

namespace Test
{
    internal class Point
    {
        private double X { get; set; }
        private double Y { get; set; }

        public Point(double x, double y)
        {
            X = x;
            Y = y;
        }
        public double GetX()
        {
            return X;
        }
        public double GetY()
        {
            return Y;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Then, the main class is written as following:

using System;

namespace Test
{
    class Program
    {
        private static int NumberOfCirclePoints = 0;
        private static Random RandomObject = new Random();
        private static double GenerateRandomDouble(double min, double max)
        {
            double d = RandomObject.NextDouble() * (max - min) + min;
            return d;
        }
        static void Main(string[] args)
        {
            Console.Write("Radius: ");
            double radius = Convert.ToDouble(Console.ReadLine());
            Console.Write("Center of the circle (eg. 10,2): ");
            string center = Console.ReadLine();
            Console.Write("How many points? ");
            int numberOfPoints = Convert.ToInt32(Console.ReadLine());

            string[] centerCoordinates = center.Split(',');
            double cx = Convert.ToDouble(centerCoordinates[0].Trim());
            double cy = Convert.ToDouble(centerCoordinates[1].Trim());
            double scx, scy;
            scx = scy = cx + radius;

            for (int i = 0; i < numberOfPoints; i++)
            {
                double cxDouble = GenerateRandomDouble(cx, scx);
                double cyDouble = GenerateRandomDouble(cy, scy);
                // calculate the distance between the circle center and the given point.
                double distance = Math.Sqrt(Math.Pow(cxDouble - cx, 2) + Math.Pow(cyDouble - cy, 2));
                // If the distance is less or equal to the radius of the circle then the given point is inside the circle area.
                // Else the given point is outisde the circle area.
                if (distance <= radius)
                    NumberOfCirclePoints++;
            }
            double PI = 4 * (Convert.ToDouble(NumberOfCirclePoints) / Convert.ToDouble(numberOfPoints));
            Console.WriteLine($"PI = {PI}");

            Console.ReadKey();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

As we notice above in for loop, I am generating a random points that exist only in the square area. With each iteration we check if each of the randomly generated points is inside the circle quarter. This can be done by calculating the distance between the center of the circle and the random point. Then, we compare the distance with the radius. If distance is smaller or equal to the radius then the point is inside the circle. At this stage, we increase NumberOfCirclePoints variable by 1.

Note: the distance formula is: d = √(x2 - x1)^2 + (y2 - y1)^2

Finally, The higher the number of points taken within the square, the higher the accuracy of the value of π.

Example:
for the same radius (let's say 100) and center C(0, 0)
1000 points ---> π = 3.208
1000000 points ---> π = 3.142564
Enter fullscreen mode Exit fullscreen mode

Thanks for reading ❤.

💖 💪 🙅 🚩
mohamadhag
Mohamad Hag

Posted on August 27, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related