3.14159265358979323846264338327950288419716939937510582097494459

March 14th, Happy PI day! 🎉

To celebrate this important day for the Mathematical and engineering community let's generate an approximation of PI using geometry and a random coordinate generator.

let's imagine a square that contains a circle of radius r, if we throw some darts randomly we can count the darts that landed inside the square (All of them) and the darts that landed inside the circle.

The ratio between the total of points that landed in the circle and the total number of points would be very close to the ratio between the area of the square and the ares of the circle

Something like this:

\[{Number Of Points In Circle \over Number Of Points} ≈ {πr^2 \over (2r)^2 }.\]

Assuming that the radius of our circle is 1, if we try to assolate π we will have the following equation

\[{π} ≈ {4} {Number Of Points In Circle \over Total Of Points}.\]

Cool! Now that we have our math sorted out, we can go ahead and create a function that generates random coordiantes between [0, 0] and [1, 1]

const randomCoor = () =>{
  return [Math.random(), Math.random()];
};

You might be wondering, how can we know if this random point is landing inside or outside the circle? Well, we can ask that question to our old friend Pythagoras.

We can calculate the distance from 0 to our point, if this distance is less than r then we can conclude that the point landed within the borders of the circle, else it landed outside of it.

\[{d} = {\sqrt{x^2 + y^2}}.\]

const insideOrOutside = (coord) => {
  const d = Math.sqrt(coord[0]**2 + coord[1]**2 );
  if (d > 1){
    return "Outside"
  } else {
    return "Inside"
  }
};

Now that our function works lets try to generate a loop and see how close we can get to π

Total of points

points inside de circle

Our approximation to PI