Recall that p is the ratio of a circles circumference to


Determining Pi Experimentally

Recall that π is the ratio of a circle's circumference to its diameter and that we can calculate the area of a circle with the formula A = π·r2. Below is a circle inscribed within the unit square.

Consider the following questions:

  • What is the ratio of the areas of the inscribed circle to that of the unit square?
  • If we pick a random point within the unit square what is the probability that the point will also lie within the circle?

If we repeat the experiment of choosing points at random an arbitrarily large number of times, the ratio of the number of points which lie within the circle to the number of points within the unit square (all of them) will approach π/4. Using the language structures we have discussed have a program that will do the above experiment an arbitrary (determined at run-time) number of times and report back the approximate value of π.

import java.util.*;

public class DeterminingPi 

{

public static boolean isInside (double x, double y)  

double distance = Math.sqrt((x * x) + (y * y));

return (distance < 1.0);

}

public static double calculatePI (int num) 

{

Random random= new Random (System.currentTimeMillis());  

int repeats = 0;

double PI = 0;

for (int i = 1; i <= num; i++)

{

double x = (random.nextDouble()) * 2 - 1.0;

double y = (random.nextDouble()) * 2 - 1.0;

if (isInside(x, y))

{

repeats++;

}

}

double dRepeats = num;

PI = (4.0 * (repeats/dRepeats));

return PI;

}

public static void main (String[] args)

{

Scanner scan = new Scanner (System.in); 

System.out.print("Please key in the number of times you want to execute the program: ");

int num = scan.nextInt();

double PI = calculatePI(num);

System.out.println ("The value of PI is about " + PI);  

scan.close();

}

}

Solution Preview :

Prepared by a verified Expert
Business Management: Recall that p is the ratio of a circles circumference to
Reference No:- TGS02657343

Now Priced at $20 (50% Discount)

Recommended (91%)

Rated (4.3/5)