Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.Scanner;
- /**
- * Write a description of class PiCalc here.
- *
- * @author Mark Davis
- * @version 12/1/2013
- */
- public class PiCalc
- {
- public static void main(String[] args)
- {
- int[] inputResults = takeInputs();
- int perTrial = inputResults[0];
- int trials = inputResults[1];
- double[] piValues = executeTrials(trials, perTrial);
- System.out.println("Estimated pi = " + computeAverageOfArray(piValues));
- }
- public static int[] takeInputs()
- {
- Scanner in = new Scanner(System.in);
- System.out.println("How many repetitions per trial?");
- String u = in.next();
- int y = Integer.parseInt(u);
- System.out.println("How many Trials?");
- String q = in.next();
- int z = Integer.parseInt(q);
- in.close();
- int[] s = {y,z};
- return s;
- }
- public static double[] executeTrials(int numTrials, int perTrial)
- {
- double[] piValues = new double[numTrials];
- for(int i = 0; (i <= numTrials -1); i++)
- {
- piValues[i] = trial(perTrial);
- System.out.printf("%6s %2s %9s %8.6f", "Trial[", (i + 1), "]: pi = ", piValues[i]);
- System.out.println();
- }
- return piValues;
- }
- public static double trial(int perTrial)
- {
- int numTotal = 0;
- int numInCircle = 0;
- for(int i = 0; (i <= perTrial); i++)
- {
- double a = randomValue(-1.0, 1.0);
- double b = randomValue(-1.0, 1.0);
- if (withinCircle(a,b))
- {
- numInCircle++;
- }
- numTotal++;
- }
- return calcPi(numInCircle, numTotal);
- }
- public static boolean withinCircle(double x, double y)
- {
- if (Math.sqrt(Math.pow(x,2) + Math.pow(y,2)) >= 1)
- return false;
- return true;
- }
- public static double randomValue(double rangeMin, double rangeMax)
- {
- Random r = new Random();
- double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
- return randomValue;
- }
- public static double calcPi(int h, int n)
- {
- return ((double)h*4)/((double)n);
- }
- public static double computeAverageOfArray(double[] x)
- {
- double total = 0;
- int depth = 0;
- for(double num: x)
- {
- depth++;
- total += num;
- }
- return total/((double)depth);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement