In a program, I need to display the approximate PI value, which is close to 3.141592653. The program is from The Art and Science of Java Chapter 6 Exercise 3.
Let me outline the exercise. Imagine there is a circle with radius r inscribed inside a square with length of 2r. If a dart is threw in a random fashion, the probability that the dart will fall in the circle is the ratio between the area of the circle and the square, which is PI*r^2/4*r^2, which is the same as PI/4. As a result, the more experiments, the more precise the the value of PI is. Now imagine we are doing it in a coordinates. Randomly choose 2 number, x and y each between -1 and 1. If x^2 + y^2 < 1, the coordinate point will fall into the circle with 1 radius centered in the middle of the coordinates.
Here is the program:
import acm.program.*;
import acm.util.*;
public class ApproxPIValue extends ConsoleProgram{
public void run() {
int total = 0; //calculating the time the dart falls into the circle.
for (int a = 0; a < 10000; a++) {
double x = rgen.nextDouble(-1.0, 1.0);
double y = rgen.nextDouble(-1.0, 1.0);
if ((Math.pow(x, 2) + Math.pow(y, 2)) < 1) {
total++;
}
}
println((double) (total / 10000)*4); // as I mentioned above, the result would be the approximate value of PI/4. By multiplying the result with 4, get the approximate PI value.//
}
/* set RandomGenerator as an instance variable. */
private RandomGenerator rgen = new RandomGenerator();
}
Another question is, is there anyway to print a String without extending any class. As you may notice in the code, I extends ConsoleProgram, which contains the println method. I know there is another method called System.out.print, but when I use it, it doesn't work, even Eclipse doesn't give any warning.