- Laura Whiting

# Determining the Value of Pi in Stata – An Example of the Monte Carlo Simulation Method

This post is a fun demonstration of how to apply the Monte Carlo method in Stata. Briefly, this is a computational method that generates many random samples based on parameters or inputs the user specifies. The more random samples you generate, the closer you will get to the true or correct distribution of samples. It is used to solve physical and mathematical problems.

An easy example of this is a coin toss experiment. Rather than physically tossing a coin over and over again, I can create a small program in Stata to simulate the tossing of a coin. I can then run this program through the **simulate** command in Stata to simulate the tossing of a coin many times. It is generally accepted that you need a minimum of 10,000 samples to get a sample distribution close to the true distribution.

**Worked Example**

In this example I use the Stata **simulate** command to determine the value of Pi using the Monte Carlo method. The calculation uses a ratio regarding a circle sitting inside a square (in 2D). The ratio of the area of the circle to the area of a square (Area circle : Area square) should equal Pi divided by 4 (pi/4). If I create a program to pick 100 points at random within the area of the square, then ~78 of those points should fall inside the circle as well (100*pi/4). I can then put this program through the **simulate **command to get Stata to run the program 1,000 times. This results in 100,000 samples and should allow me to determine the value of pi reasonably accurately. The program for this is as follows:

And now, to run this through simulate to get my 100,000 samples I use the following commands:

This produces the following output in Stata:

By looking at the mean shown by **summarize** we can see that we estimated the value of Pi correctly to two decimal places (3.14016). Because I have set the random seed for my simulate command above, you should be able to run this command with the genPI program and get the exact same result as is shown here.