R Programming Tutorial – How to Compute PI using Monte Carlo in R?


In last tutorial, we learn the basics of R programming by the simple example to plot the sigmoid function. This tutorial will continue to help you understand how powerful R is to handle the vectors (arrays).

We know that the math constant tex_af13d5f3905a7f5cfa284795beaccdb6 R Programming Tutorial - How to Compute PI using Monte Carlo in R? algorithms math monte carlo Monte Carlo Simulation Monte Carlo Simulation Algorithm R programming tutorial can be approximated by 4 times of the number of points inside a 1/4 circle divided by the total number of points. This is known as the Monte Carlo computation, which is to create as many random sample points as possible and count the statistics.

We can set the random seed by using set.seed() function (you can set to a constant number in order to reproduce the same ‘random’ data sets), e.g.:

set.seed(0.234234)

Now, we can generate two vectors given a length, for example:

# both x and y contains now 100000 random numbers
x=runif(100000)
y=runif(100000)

These random numbers are float numbers between 0 and 1, which can be visualized as 100000 points. So we can now compute their distance to the (0, 0), or the radius of the circle.

z=sqrt(x^2+y^2)

Now, z is also length of 100000. We next need to count how many of the distances in z vector are smaller than 1 (falling inside the 1/4 circle). We can use which to return all indices of the array given a condition.

# The following returns the indices vector when z is less than 1
which(z<1)

To count the points, we use the length function. And the PI is finally estimated in a straightforward expression. Remember, this is just the approximation and the accuracy does improve when the number of samples gets larger and larger.

length(which(z<=1))*4/length(z)
[1] 3.1454

Plot the points

We can plot the points (that fall inside the circle) using (default black color if color is not specified):

plot(x[which(z<=1)],y[which(z<=1)],xlab="X",ylab="Y",main="Monte Carlo")

and points outside the circle (noted in blue color) can be added to the same plot using:

points(x[which(z>1)],y[which(z>1)],col='blue')

This finally gives the plot:

monte-carlo-pi-in-r R Programming Tutorial - How to Compute PI using Monte Carlo in R? algorithms math monte carlo Monte Carlo Simulation Monte Carlo Simulation Algorithm R programming tutorial

monte-carlo-pi-in-r

You see? No for/while loops, just 4 statements in R!

R Tutorial

Monte Carlo Simulation Algorithms to compute the Pi based on Randomness:

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
1045 words
Last Post: How to Add To Favorite using Javascript?
Next Post: How to Solve 'Mobile Data Disconnected' on HTC One M9?

The Permanent URL is: R Programming Tutorial – How to Compute PI using Monte Carlo in R?

Leave a Reply