P6.14. Program the following simulation: Darts are thrown at random points onto
ID: 3639069 • Letter: P
Question
P6.14. Program the following simulation: Darts are thrown at random points onto the square with corners (1,1) and (-1,-1). If the dart lands inside the unit circle (that is, the circle with center (0,0) and radius 1), it is a hit. Otherwise it is a miss. Run this simulation and use it to determine an approximate value for p (PI)Your main class should be called DartSimulator. The DartSimulator should ask the user how many throws to make and then display the value of PI.
Use the following class in your solution:
public class Dart
{
public Dart() { . . . }
/**
Throws a dart into the square [-1,1] x [1,1] and records
if it hits the unit circle.
*/
public void throwIntoSquare() { . . . }
/**
Gets the number of hits inside the unit circle.
@return hits number of hits
*/
public int getHits() { . . . }
/**
Gets the number of tries.
@return the number of times the dart was thrown
*/
public int getTries() { . . . }
/**
Estimates the value of PI.
@return the value of PI approximation
*/
public double getPI() { . . . }
// Instance Fields
. . .
}
Explanation / Answer
please rate - thanks
import java.util.*;
public class DartSimulator
{
public static void main(String [] args)
{Scanner input=new Scanner(System.in);
int sets,tosses=10;
System.out.print("how many sets of data do you want? ");
sets=input.nextInt();
Dart p=new Dart();
for(int j=0;j<sets;j++)
p.throwIntoSquare();
System.out.println("calculated pi, after "+sets+" tosses= "+p.getPI());
}
}
----------------------------------
import java.util.*;
public class Dart
{public Dart() { in=0;
tries=0; }
/**
Throws a dart into the square [-1,1] x [1,1] and records
if it hits the unit circle.
*/
public void throwIntoSquare() {
Random r=new Random();
x=r.nextDouble()*2-1;
y=r.nextDouble()*2-1;
if(Math.sqrt(x*x+y*y)<=1.)
in++;
tries++;
}
/**
Gets the number of hits inside the unit circle.
@return hits number of hits
*/
public int getHits() {return in; }
/**
Gets the number of tries.
@return the number of times the dart was thrown
*/
public int getTries() {return tries ;}
/**
Estimates the value of PI.
@return the value of PI approximation
*/
public double getPI() {return 4.0*((double)in/tries);
}
private double x,y;
private int in,tries;
// Instance Fields
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.