# Estimating Pi using the Monte Carlo method

I built a numerical algorithm to find pi! __CLICK HERE__ for the source code.

Happy Pi Day 2023! To celebrate, I built a Monte Carlo method based pi estimator code, which uses random sampling to approximate the value of pi. I’ve explained the concept below.

The basic idea is to randomly generate points within a square, and then determine how many of those points fall within the inscribed circle. By comparing the ratio of points in the circle to the total number of points generated, we can estimate the value of pi.

The ratio of the number of accepted to the rejected points help us estimate the area circle which in turn estimates pi. Here’s the math:

The area of the square is As = 1.

The area of the circle is Ac = pi/4.

The ratio of the two areas Ar = pi/4

Solving for pi, we get pi = 4*Ar.

Here are some results when I ran my code with various sample sizes and calculated the estimated value of pi. As expected, the accuracy improved as the number of samples increased.

Here are my results:

1,000 samples: 3.1601

10,000 samples: 3.1544

100,000 samples: 3.1433

1,000,000 samples: 3.1436

10,000,000 samples (after a few seconds of computation): 3.1419

As you can see, the estimated value of pi gets closer to the true value (3.14159265359...) as the number of samples increases. This is a great example of how numerical methods can be used to solve complex problems and estimate values with a high degree of accuracy.

The animation above shows how the estimated value approaches the true value for increasing number of samples/points/iterations (left); and points being randomly placed inside a unit square (right) which are either accepted (red) or rejected (blue).

__CLICK HERE__ for the source code.

#PiDay#MonteCarloMethods#NumericalMethods#DataScience#MATLAB#FORTRAN#animation#computational#appliedmathematics#piday2023