Created
February 23, 2012 04:26
-
-
Save mimshwright/1890194 to your computer and use it in GitHub Desktop.
Solution to Monte Carlo problem for Coding Dojo Feb 2012 by Mims H. Wright
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
/** | |
* @author Mims H. Wright - [email protected] | |
*/ | |
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