Approximate π (Pi) through code

Manish Kumar
2 min readApr 27, 2024

Approximate π using a random function that returns a random value between 0 and 1

We can leverage the Monte Carlo random algorithm to approximate the value of π.

Theory:

  • Start with a Cartesian plane with coordinates ranging from -1 to 1 on both the x and y axes, creating a 2x2 box. Fill this box with randomly generated points on this grid.
  • Determine the count of points, denoted as C, that lie within a distance of 1 from the origin (0,0)
  • For example, a point such as (0.1,0) falls within the specified distance from the origin, while a point like (-0.95,0.95) falls away from the origin.

Let's see this in the diagram:

In the above diagram, the first quadrant is filled with the red dots. These are the points which fall inside the circle.

Area of first quadrant = r*r (r = 1)

Area of circle = π * r * r

Area of red part = Area of circle / 4 (as this is the 1/4th part of the circle)

So value of π = 4 * Area of red part / total area in the first quadrant

Below is the code:

    public static void main(String[] args) {
Random random = new Random();
int totalPointInCircle = 0;
int range = 10000000;
for (int i = 0; i < range; i++) {
double x = random.nextDouble();
double y = random.nextDouble();

double distance = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
if (distance < 1) {
++totalPointInCircle;
}
}
System.out.println((float) 4 * totalPointInCircle / range);
}

Happy Learning!!!

--

--