Java Reference
In-Depth Information
Suppose we generate two random fractions, that is, two values between 0 and 1; call these values x and y .
Since 0 £ x £ 1 and 0 £ y £ 1, it follows that the point ( x , y ) lies within S.
This point will also lie within C if x 2 + y 2 £ 1.
If we generate n pairs of random fractions, we have, in fact, generated n points within S. For each of these points,
we can determine whether the point lies with C. Suppose m of these n points fall within C. From our discussion, we
can assume that the following approximation holds:
area of C m
=
area of S
n
π and the area of S is 1. So, the following holds:
The area of C is 4
π
m
n
=
4
Hence:
π = 4 m
n
.
Based on this, we write Program P6.8 to estimate p.
Program P6.8
import java.util.*;
public class Pi {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int inC = 0;
System.out.printf("\nHow many numbers to use? ");
int inS = in.nextInt();
for (int j = 1; j <= inS; j++) {
double x = Math.random();
double y = Math.random();
if (x * x + y * y <= 1) inC++;
}
System.out.printf("\nAn approximation to pi is %5.3f\n", 4.0 * inC/inS);
} //end main
} //end class Pi
The value of p to 3 decimal places is 3.142. When run with 1000 numbers, this program gave 3.132 as an
approximation to p. When run with 2000 numbers, it gave 3.140 as the approximation.
 
Search WWH ::




Custom Search