Exercise 3: Computing using Monte Carlo Simulation Consider a circle of radius r
ID: 3873270 • Letter: E
Question
Exercise 3: Computing using Monte Carlo Simulation Consider a circle of radius r inscribed inside a square of side 2r. The area of the circle is and the area of the square is (2r)2. If we pick a point at random anywhere inside the square, then we can calculate that the probability that the point also falls inside the circle is: Now image an experiment where we choose many different random points inside the square and count the total number of points that fall inside the circle Ninside and the total number that fall outside the circle Noutside. If we take a large number of sample points, we can accurately estimate the probability p as: p = Ninside / (Ninside + Nout side) and from our estimate of p, we can then find an estimate for as being = 4p. This type of randomised algorithm is called the Monte Carlo Method. Although it is not an efficient way to compute , it is generally a very useful method of solving problems in physics, engineering and mathematics which cannot be solved analytically. Task: Implement the random experiment described above, using Java. Use your code to find an estimate for . Investigate how the expected accuracy of the estimate for depends on the number of samples usedExplanation / Answer
The following program calculates value of Pi for 200000000 sample points and the value comes out as 2.94005874
. the expected accuracy has increases as number of point increases. With 200 sample points the value is 2.86
import java.util.*;
public class DemoPi{
public static void main(String[] args){
double rad = 20;
double n_inside = 0;
Random rand = new Random();
for (long i = 0; i<200000000; i++){
int x = rand.nextInt(20) + 1;
int y = rand.nextInt(20) + 1;
if (Math.sqrt(x*x + y*y) <= rad){
n_inside++;
}
}
double pi = (n_inside/200000000) * 4;
System.out.println("Value of pi is :" + pi);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.