Java Reference
In-Depth Information
each sample. When the simulation is completed, the averages, or other statistics of
interest from the observed values are printed out.
A typical example of a simulation is the modeling of customer queues at a bank or a
supermarket. Rather than observing real customers, one simulates their arrival and
their transactions at the teller window or checkout stand in the computer . One can try
different staffing or building layout patterns in the computer simply by making
changes in the program. In the real world, making many such changes and measuring
their effects would be impossible, or at least, very expensive.
260
261
S ELF C HECK
9. How do you use a random number generator to simulate the toss of a
coin?
10. Why is the NeedleSimulator program not an efficient method for
computing ƚ?
A DVANCED T OPIC 6.5: Loop Invariants
Consider the task of computing a n , where a is a floating-point number and n is a
positive integer. Of course, you can multiply a . a . È . a , n times, but if n
is large, you'll end up doing a lot of multiplication. The following loop computes
a n in far fewer steps:
double a = . . .;
int n = . . .;
double r = 1;
double b = a;
int i = n;
while (i > 0)
{
if (i % 2 == 0) // n is even
{
b = b * b;
i = i / 2;
}
else
{
r = r * b;
Search WWH ::




Custom Search