mimshwright / montecarlo.java Created February 23, 2012

SSH clone URL

You can clone with HTTPS or SSH.

Solution to Monte Carlo problem for Coding Dojo Feb 2012 by Mims H. Wright

View montecarlo.java
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 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); } }