Created
October 10, 2016 08:46
-
-
Save oskar-j/f2fd93f5d08b87b7e0af43f2d6d5b3b2 to your computer and use it in GitHub Desktop.
Monte carlo simulation of the PI value
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
package model; | |
public class MonteCarloToolbox { | |
public static boolean[] dartThrow(int r, int d) { | |
boolean[] booleanArray = new boolean[d]; | |
for (int i = 0; i < d; i++) { | |
double xCoord = Math.random() * r; | |
double yCoord = Math.random() * r; | |
// condition check | |
if ((Math.pow(xCoord,2) + Math.pow(yCoord,2)) <= r*r) { | |
booleanArray[i] = true; | |
} else { | |
booleanArray[i] = false; | |
} | |
} | |
return booleanArray; | |
} | |
// calculating pi from throwing results | |
public static double piEstimater(boolean[] h, int d) { | |
int trueCounter = 0; | |
for (int i = 0; i < h.length; i++) { | |
if (h[i] == true) { | |
trueCounter++; | |
} | |
} | |
return 4 * ((double) trueCounter / d); | |
} | |
// printing results | |
public static void printer(double[] a) { | |
System.out.println(" Pi Estimation Tool "); | |
System.out.println("-------------------------"); | |
for (int i = 0; i < a.length; i++) { | |
System.out.print("Trial [" + i + "]: π = "); | |
System.out.printf("%6f\n", a[i]); | |
} | |
} | |
public static void main(String[] args) { | |
int radius = 1; | |
int darts; | |
int trials; | |
// Enter the number of darts to calculate for | |
darts = 50*1000; | |
// Enter the number of trials to calculate for | |
trials = 20; | |
double[] arrayOfEstimates = new double[trials]; | |
for (int i = 0 ; i < arrayOfEstimates.length ; i++) { | |
boolean[] hitCounter = dartThrow(radius, darts); | |
double piEstimate = piEstimater(hitCounter, darts); | |
arrayOfEstimates[i] = piEstimate; | |
} | |
printer(arrayOfEstimates); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment