Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Estimating The Value Of PI By Throwing Darts

$
0
0
In this program I'm supposed to write I need to estimate the value of PI by running simulations of darts being thrown onto a square sheet of paper with a circle in the middle of the paper. So if the side length of the square sheet of paper is 2 then the radius of the circle is 1. I was told to estimate the value of PI with the formula of
PI = 4 * (h / n)
. h is the number of times the dart land in the circle and n is the total number of throws. I am then told to see if the dart hits the circle with this formula
x^2 + y^2 <= 1
. Would that formula be true even if the radius of the circle is more than 1? I did my best to write the program but I seem to be getting values like 0.785476 which is not even close to 3.14. Here is my main class:

import java.util.Random;
import java.util.Scanner;


public class Darts {
	
	public static void main(String[] args) {
		
		long simulationsToRun = 0;
		int trialsToRun = 0;
		int circleRadius = 1;
		double estimatePiValue = 0.0;
		Random rand = new Random();
		
		System.out.print("How many times would you like to throw the darts each trial? You may enter a value up to " + Long.MAX_VALUE + ": ");
		Scanner s = new Scanner(System.in);
		simulationsToRun = s.nextLong();
		
		System.out.println("\nHow many trials would you like to run? ");
		trialsToRun = s.nextInt();
		double[] values = new double[trialsToRun];
		
		double x = 0.0, y = 0.0;
		System.out.println();
		
		for (int j = 0; j <= trialsToRun; j++) {
			
			long timesHitCircle = 0;
			
			for (long k = 0; k <= simulationsToRun; k++) {
				
				x = rand.nextDouble() * circleRadius * 2;
				y = rand.nextDouble() * circleRadius * 2;
				
				timesHitCircle += (Math.pow(x, 2) + Math.pow(y, 2) <= circleRadius ? 1 : 0);
				
			}
			
			values[j] = 4.0 * ((double)timesHitCircle / (double)simulationsToRun);
			
			System.out.println("Trial [" + (j + 1) + "]: PI = " + values[j]);
			
		}
		
		s.close();
		
		for (double val : values) {
			estimatePiValue += val;
		}
		
		estimatePiValue /= trialsToRun;
		
		System.out.println("Estimate of PI = " + estimatePiValue);

	}

}



Couldn't I check if the dart hits the circle by taking the x and y coordinate the the power of two, adding them together, squaring them, and seeing if it is less than or equal to the radius and if it isn't then that means it is outside of the circle?

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>