Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Calculate the value of pi by simulating throwing darts at a dart board.
- *
- * @author Wes Mills
- * @version 11/18/18
- */
- import java.util.Scanner;
- import java.io.File;
- import java.io.IOException;
- import java.io.PrintWriter;
- public class EstimatePi
- {
- public static int[] dartSuccesses(int z, int numOfDarts, int numOfTrials)
- {
- int counter = 0;
- int counter2 = 0;
- int index = 0;
- int[] trials = new int [numOfTrials];
- for(int t = 0; counter < numOfTrials; counter++) //Counts number of trials done
- {
- for(z = 0; counter2 < numOfDarts; counter2++) //Simulates amount of time dart would hit the board, randomly
- {
- double x = Math.pow(Math.random(), 2);
- double y = Math.pow(Math.random(), 2);
- if(x + y <= 1)
- {
- z++;
- }
- }
- trials[index] = z;
- index++;
- }
- return trials; //z being the number of times the dart hit the board
- }
- public static double dartAverage(int[] dartHits) //Estimates what pie is based on average of results
- {
- double dartAvg = 0.0;
- int counter = 0;
- for(int darts : dartHits)
- {
- dartAvg += dartAvg;
- counter++;
- }
- dartAvg /= counter;
- return dartAvg;
- }
- public static void main(String[] args)throws IOException
- {
- Scanner in = new Scanner(System.in);
- int counter = 1;
- System.out.println("Please enter the number of darts you'd like to see estimated per trial.");
- int dartCount = in.nextInt();
- System.out.println("Please enter the amount of trials you'd like to see.");
- int trialCount = in.nextInt();
- int hits = 0;
- int[] dartHits = dartSuccesses(hits, dartCount, trialCount);
- double piEstimate = dartAverage(dartHits);
- //Output
- System.out.println("\nHow many darts per trial? " + dartCount);
- System.out.println("\nHow many trials? " + trialCount);
- System.out.println("");
- for(int index = 0; index < trialCount; index++)
- {
- System.out.printf("%0s%0d%0s%10d%n", "Trial [ ", counter, "]: pi = ", dartHits[index]);
- counter++;
- }
- System.out.printf("%0s%10d" , "Estimate of pi = ", piEstimate);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement