Skip to content

@mimshwright /montecarlo.java
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Solution to Monte Carlo problem for Coding Dojo Feb 2012 by Mims H. Wright
import java.io.*;
/**
* @author Mims H. Wright - mims@mimswright.com
*/
class montecarlo {
// To run, on command line type:
// javac montecarlo.java
// java montecarlo
public static void main ( String[] args) {
int reps = 0;
// read the number of reps from the command-line
System.out.println("Enter number of repititions then press enter.");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
reps = Integer.parseInt(br.readLine());
} catch (IOException ioe) {
System.out.println("Error reading reps!");
System.exit(1);
}
System.out.println("Calculating π in " + reps + " steps.");
int i = 0, inCircle = 0;
double x = 0.0, y = 0.0, d = 0.0;
while (i++ < reps) {
// generate a random point
x = Math.random();
y = Math.random();
// Find the distance from the origin.
d = Math.sqrt( x*x + y*y );
// If it's less than the radius of the circle, it's inside the circle.
inCircle += d < 1 ? 1 : 0;
}
double pi = (double) inCircle / reps * 4.0;
System.out.println("Pi is roughly " + pi + " ( " + inCircle + "/" + reps + ")");
System.exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.