Java Reference
In-Depth Information
maxCount be the total number of random numbers generated between 2 and 3. The user
will supply maxCount .
Let
amountLess be the count of those numbers less than 5 .
Let
amountLess
2+ maxCount
An approximation to
5 is given by
.
To understand the idea behind the method, consider the line segment between 2 and 3 and let the point r
represent the square root of 5.
If we imagine the line between 2 and 3 completely covered with dots, we would expect that the number of dots
between 2 and r would be proportional to the length of that segment. In general, the number of dots falling on any line
segment would be proportional to the length of that segment—the longer the segment, the more dots will fall on it.
Now, each random number between 2 and 3 represents a dot on that line. We would expect that the more
numbers we use, the more accurate would be our statement that the length of the line between 2 and r is proportional
to the number of numbers falling on it and, hence, the more accurate our estimate.
Program P6.7 calculates an estimate for 5 based on this method. Remember that Math.random generates a
random fraction.
When run with 1,000 numbers, this program gave 2.234 as the square root of 5. The value of 5 is 2.236 to three
decimal places.
Program P6.7
import java.util.*;
public class Root5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("\nHow many numbers to use? ");
int maxCount = in.nextInt();
int amountLess = 0;
for (int j = 1; j <= maxCount; j++) {
double r = 2 + Math.random();
if (r * r < 5) ++amountLess;
}
System.out.printf("\nThe square root of 5 is about %5.3f\n",
2 + (double) amountLess / maxCount);
} //end main
} //end class Root5
6.10.2 Estimating p
Consider Figure 6-1 , which shows a circle within a square.
 
Search WWH ::




Custom Search