Advertisement
Guest User

Untitled

a guest
Nov 20th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. /**
  2. * Calculate the value of pi by simulating throwing darts at a dart board.
  3. *
  4. * @author Wes Mills
  5. * @version 11/18/18
  6. */
  7. import java.util.Scanner;
  8. import java.io.File;
  9. import java.io.IOException;
  10. import java.io.PrintWriter;
  11. public class EstimatePi
  12. {
  13. public static int[] dartSuccesses(int z, int numOfDarts, int numOfTrials)
  14. {
  15. int counter = 0;
  16. int counter2 = 0;
  17. int index = 0;
  18. int[] trials = new int [numOfTrials];
  19. for(int t = 0; counter < numOfTrials; counter++) //Counts number of trials done
  20. {
  21. for(z = 0; counter2 < numOfDarts; counter2++) //Simulates amount of time dart would hit the board, randomly
  22. {
  23. double x = Math.pow(Math.random(), 2);
  24. double y = Math.pow(Math.random(), 2);
  25. if(x + y <= 1)
  26. {
  27. z++;
  28. }
  29. }
  30. trials[index] = z;
  31. index++;
  32. }
  33. return trials; //z being the number of times the dart hit the board
  34. }
  35.  
  36. public static double dartAverage(int[] dartHits) //Estimates what pie is based on average of results
  37. {
  38. double dartAvg = 0.0;
  39. int counter = 0;
  40. for(int darts : dartHits)
  41. {
  42. dartAvg += dartAvg;
  43. counter++;
  44. }
  45. dartAvg /= counter;
  46. return dartAvg;
  47. }
  48.  
  49.  
  50. public static void main(String[] args)throws IOException
  51. {
  52. Scanner in = new Scanner(System.in);
  53. int counter = 1;
  54.  
  55. System.out.println("Please enter the number of darts you'd like to see estimated per trial.");
  56. int dartCount = in.nextInt();
  57. System.out.println("Please enter the amount of trials you'd like to see.");
  58. int trialCount = in.nextInt();
  59.  
  60. int hits = 0;
  61. int[] dartHits = dartSuccesses(hits, dartCount, trialCount);
  62. double piEstimate = dartAverage(dartHits);
  63.  
  64. //Output
  65. System.out.println("\nHow many darts per trial? " + dartCount);
  66. System.out.println("\nHow many trials? " + trialCount);
  67. System.out.println("");
  68. for(int index = 0; index < trialCount; index++)
  69. {
  70. System.out.printf("%0s%0d%0s%10d%n", "Trial [ ", counter, "]: pi = ", dartHits[index]);
  71. counter++;
  72. }
  73. System.out.printf("%0s%10d" , "Estimate of pi = ", piEstimate);
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement