Advertisement
markd315

Untitled

Dec 1st, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.Scanner;
  3.  
  4. /**
  5. * Write a description of class PiCalc here.
  6. *
  7. * @author Mark Davis
  8. * @version 12/1/2013
  9. */
  10. public class PiCalc
  11. {
  12. public static void main(String[] args)
  13. {
  14. int[] inputResults = takeInputs();
  15. int perTrial = inputResults[0];
  16. int trials = inputResults[1];
  17. double[] piValues = executeTrials(trials, perTrial);
  18. System.out.println("Estimated pi = " + computeAverageOfArray(piValues));
  19. }
  20. public static int[] takeInputs()
  21. {
  22. Scanner in = new Scanner(System.in);
  23. System.out.println("How many repetitions per trial?");
  24. String u = in.next();
  25. int y = Integer.parseInt(u);
  26. System.out.println("How many Trials?");
  27. String q = in.next();
  28. int z = Integer.parseInt(q);
  29. in.close();
  30. int[] s = {y,z};
  31. return s;
  32. }
  33. public static double[] executeTrials(int numTrials, int perTrial)
  34. {
  35. double[] piValues = new double[numTrials];
  36. for(int i = 0; (i <= numTrials -1); i++)
  37. {
  38. piValues[i] = trial(perTrial);
  39. System.out.printf("%6s %2s %9s %8.6f", "Trial[", (i + 1), "]: pi = ", piValues[i]);
  40. System.out.println();
  41. }
  42. return piValues;
  43. }
  44. public static double trial(int perTrial)
  45. {
  46. int numTotal = 0;
  47. int numInCircle = 0;
  48. for(int i = 0; (i <= perTrial); i++)
  49. {
  50. double a = randomValue(-1.0, 1.0);
  51. double b = randomValue(-1.0, 1.0);
  52. if (withinCircle(a,b))
  53. {
  54. numInCircle++;
  55. }
  56. numTotal++;
  57. }
  58. return calcPi(numInCircle, numTotal);
  59. }
  60. public static boolean withinCircle(double x, double y)
  61. {
  62. if (Math.sqrt(Math.pow(x,2) + Math.pow(y,2)) >= 1)
  63. return false;
  64. return true;
  65. }
  66. public static double randomValue(double rangeMin, double rangeMax)
  67. {
  68. Random r = new Random();
  69. double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
  70. return randomValue;
  71. }
  72. public static double calcPi(int h, int n)
  73.  
  74. {
  75. return ((double)h*4)/((double)n);
  76. }
  77. public static double computeAverageOfArray(double[] x)
  78. {
  79. double total = 0;
  80. int depth = 0;
  81. for(double num: x)
  82. {
  83. depth++;
  84. total += num;
  85. }
  86. return total/((double)depth);
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement