public class MonteCarlo { public static void main(String args[]) { final int N =
ID: 675174 • Letter: P
Question
public class MonteCarlo {
public static void main(String args[]) {
final int N = 5000;
int numInside = 0;
double X, Y, radius, mypi;
for (int i=0; i<N; i++) {
/* make a throw: get new x and new y */
X = newRand(-1., 1.);
Y = newRand(-1., 1.);
/* check if throw inside circle */
radius = findRadius(X, Y);
if (radius < 1.0) { /* increment counter if inside circle */
numInside++;
}
}
/* find ratio */
/* calculate pi */
mypi = 4*numInside / (float) N;
System.out.println("Pi = " + mypi);
}
}
In the above java code method is missing and we need to add below method.
There are two new methods we need to write for the new version. The first one is newRand():
newRand() returns a random double in the range low to high. Hence, in the new version of the Monte Carlo simulation program, when we generate random x and y coordinates for a throw, the new statements are:
The second method is findRadius():
findRadius() returns the distance of the point (x, y) from the point (0, 0).
Explanation / Answer
public class MonteCarlo {
private static double newRand(double low,double high){
Random r = new Random();
return (double)r.nextInt(high-low) + low;
}
private static double findRadius(double x,double y){
return Math.sqrt(x*x + y*y);
}
public static void main(String args[]) {
final int N = 5000;
int numInside = 0;
double X, Y, radius, mypi;
for (int i=0; i<N; i++) {
/* make a throw: get new x and new y */
X = newRand(-1., 1.);
Y = newRand(-1., 1.);
/* check if throw inside circle */
radius = findRadius(X, Y);
if (radius < 1.0) { /* increment counter if inside circle */
numInside++;
}
}
/* find ratio */
/* calculate pi */
mypi = 4*numInside / (float) N;
System.out.println("Pi = " + mypi);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.