One method to estimate the value of π is by applying the Monte Carlo method. Let’s consider a circle inscribed in a square. Then for a radius r, we have:

Image for post

Image by Author

Image for post

Image by Author (written in Latex)

Example Using R

Below, we represent how we can apply the Monte Carlo Method in R to estimate the π.

## set the seed for reproducility

set.seed(5)
## number of simulations
n=1000000
## generate the x1 and x2 co-ordinates from uniform
## distribution taking values from -1 to 1
x1<-runif(n, min=-1, max=1)
x2<-runif(n, min=-1, max=1)
## Distrance of the points from the center (0,0)
z<-sqrt(x1^2+x2^2)
## the area within the circle is all the z
## which are smaller than the radius^2
## in our case radius=1
4*sum((z<=1))/length(z)

And we get:

[1] 3.14204

#python #pi #probability #monte-carlo-simulation #rstats

Estimate Pi With Monte Carlo
1.15 GEEK