• Tidak ada hasil yang ditemukan

Estimating p

Dalam dokumen Pelajari tentang Advanced topics in Java (Halaman 184-189)

Random Numbers, Games, and Simulation

6.10 Estimating Numerical Values Using Random Numbers

6.10.2 Estimating p

Consider Figure 6-1, which shows a circle within a square.

If you close your eyes and keep stabbing at the diagram repeatedly with a pencil, you may end up with something like Figure 6-2 (considering only the dots that fall within the diagram).

Figure 6-1. Circle within a square

Figure 6-2. Circle within a square after stabbing with pencil

S

C

(1, 1) (0, 1)

(0, 0) (1, 0)

Figure 6-3. Quarter circle and a square

Note that some dots fall inside the circle and some fall outside the circle. If the dots were made “at random,”

it seems reasonable to expect that the number of dots inside the circle is proportional to the area of the circle—the larger the circle, the more dots will fall inside it.

Based on this, we have the following approximation:

area of circle number of dots inside circle area of square=number of dots inside square

Note that the number of dots inside the square also includes those inside the circle. If we imagine the entire square filled with dots, then the previous approximation will be quite accurate. We now show how to use this idea to estimate p.

Consider Figure 6-3.

C is a quarter circle of radius 1; S is a square of side 1.

•฀

Area of C =

•฀ 4

π Area of S = 1.

A point (x, y) within C satisfies x

•฀ 2 + y2 £ 1, x ³ 0, y ³ 0.

A point (x, y) within S satisfies 0

•฀ £ x £ 1, 0 £ y £ 1.

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 x2 + y2 £ 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 The area of C is

4

π and the area of S is 1. So, the following holds:

4= m

n π

Hence:

π = 4m 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.

EXERCISES 6

1. Write a program to request two numbers, m and n, and print 25 random numbers from m to n.

2. Explain the difference between random and pseudorandom numbers.

3. Modify Program P6.3 to give a user problems in subtraction.

4. Modify Program P6.3 to give a user problems in multiplication.

5. Modify Program P6.3 to incorporate a scoring system. For example, for two attempts at a

problem, you can give 2 points for a correct answer on the first attempt and 1 point for a correct answer on the second attempt.

6. Rewrite Program P6.3 so that it presents the user with a menu that allows him to choose

what kinds of problems he gets (addition, subtraction, or multiplication).

7. Write a program to simulate 1,000 throws of a die and determine the number of 1s, 2s, 3s,

4s, 5s, and 6s that show. Write the program (a) without using an array and (b) using an array.

8. Write a program to simulate the weather for 60 days using the probabilities in Section 6.7.

9. In the manufacture of electric bulbs, the probability that a bulb is defective is 0.01. Simulate

the manufacture of 5,000 bulbs, indicating how many are defective.

10. A die is weighted such that 1s and 5s come up twice as often as any other number. Simulate

1,000 throws of this die, indicating the frequency with which each number occurs.

11. Modify Program P6.6 to calculate the average waiting time for customers and the total idle

time for each counter.

12. One-Zero is a game that can be played among several players using a six-sided die. On his turn,

a player can throw the die as many times as he wants. His score for that turn is the sum of the numbers he throws provided he does not throw a 1. If he throws a 1, his score is 0. Suppose a player decides to adopt the strategy of ending his turn after seven throws. (Of course, if he throws a 1 before the 7

th

throw, he must end his turn.) Write a program to play 10 turns using this strategy. For each turn, print the score obtained. Also, print the average score for the 10 turns.

Generalize the program to request values for

numTurns

and

maxThrowsPerTurn

and print the results as described.

13. Write a program to simulate the game of Snakes and Ladders. The board consists of 100

squares. Snakes and ladders are input as ordered pairs of numbers, m and n. For example, the pair

17 64

means that there is a ladder from 17 to 64, and the pair

99 28

means that there is a snake from 99 to 28.

Simulate the playing of 20 games, each game lasting a maximum of 100 moves. Print the number of games that were completed in the 100 moves and the average number of moves per game for completed games.

14. Write a program to play a modified game of Nim (Section 6.6) in which there are two heaps

of matches and a player, on his turn, may choose from either one. However, in this case, a

player wins if he picks up the last match.

15. Using the traffic lights data in Section 6.8, write a program to simulate the situation at the

lights for a 30-minute period. Print the number of cars in each queue each time the light changes.

16. Write a program to estimate the square root of 59.

17. Write a program to read a positive integer n and estimate the square root of n.

18. Write a program to read a positive integer n and estimate the cube root of n.

19. Write a program to simulate the collection of bottle caps to spell APPLE. In every 100 caps,

A and E occur 40 times each, P occurs 10 times and L occurs 10 times. Do 50 simulations and print the average number of caps per simulation.

20. The lottery requires people to pick seven numbers from the numbers 1 to 40. Write a

program to randomly generate and print five sets of seven numbers each (one set per line).

No number is to be repeated in any of the sets; that is, exactly 35 of the 40 numbers must be used. If a number (p, say) is generated that has been used already, the first unused number after p is used. (Assume that 1 follows 40.) For example, if 15 is generated but has been used already, 16 is tried, but if this has been used, 17 is tried, and so on, until an unused number is found.

21. A function f(x) is defined for 0 £ x £ 1, such that 0 £ f(x) < 1 for all 0 £ x < 1. Write a

program to estimate the integral of f(x) from 0 to 1. Hint: estimate the area under the curve by generating points (x, y ), 0 £ x < 1, 0 £ y < 1.

22. A gambler pays $5 to play the following game. He throws two six-sided dice. If the sum of

the two numbers thrown is even, he loses his bet. If the sum is odd, he draws a card from

a standard pack of 52 playing cards. If he draws an ace, 3, 5, 7 or 9, he is paid the value of

the card plus $5 (ace counts as 1). If he draws any other card, he loses. Write a program to

simulate the playing of 20 games and print the average amount won by the gambler

per game.

Dalam dokumen Pelajari tentang Advanced topics in Java (Halaman 184-189)