Java Reference
In-Depth Information
258
Typical Output
6 5 6 3 2 6 3 4 4 1
Typical Output (Second Run)
3 2 2 1 6 5 3 4 1 2
As you can see, this program produces a different stream of simulated die casts every
time it is run.
Actually, the numbers are not completely random. They are drawn from very long
sequences of numbers that don't repeat for a long time. These sequences are computed
from fairly simple formulas; they just behave like random numbers. For that reason,
they are often called pseudorandom numbers. Generating good sequences of numbers
that behave like truly random sequences is an important and wellɨstudied problem in
computer science. We won't investigate this issue further, though; we'll just use the
random numbers produced by the Random class.
To run the Buffon needle experiment, we have to work a little harder. When you
throw a die, it has to come up with one of six faces. When throwing a needle,
however, there are many possible outcomes. You must generate two random numbers:
one to describe the starting position and one to describe the angle of the needle with
the xɨaxis. Then you need to test whether the needle touches a grid line. Stop after
10,000 tries.
Let us agree to generate the lower point of the needle. Its xɨcoordinate is irrelevant,
and you may assume its y ɨ coordinate y low to be any random number between 0 and
2. However, because it can be a random floatingČpoint number, we use the
nextDouble method of the Random class. It returns a random floating ɨ point
number between 0 and 1. Multiply by 2 to get a random number between 0 and 2.
The angle Ƌ between the needle and the xɨaxis can be any value between 0 degrees
and 180 degrees. The upper end of the needle has yɨcoordinate
y high
=
y low
+ sin ( Ǒ)
The needle is a hit if y high is at least 2. See Figure 4 .
Search WWH ::




Custom Search