Java Reference
In-Depth Information
However, it is often convenient to drop the “pseudo” prefix and refer to them as ran-
dom numbers.
Random generatesitssequenceofrandomnumbersbystartingwithaspecial48-bit
value that is known as a seed . This value is subsequently modified by a mathematical
algorithm, which is known as a linear congruential generator .
Note Check out Wikipedia's “Linear congruential generator” entry ( ht-
tp://en.wikipedia.org/wiki/Linear_congruential_generator )
to learn about this algorithm for generating random numbers.
Random declares a pair of constructors:
Random() createsanewrandomnumbergenerator.Thisconstructorsetsthe
seedoftherandomnumbergeneratortoavaluethatisverylikelytobedistinct
from any other call to this constructor.
Random(long seed) creates a new random number generator using its
seed argument.Thisargumentistheinitialvalueoftherandomnumbergener-
ator'sinternalstate,whichthe protected int next(int bits) meth-
od maintains.
Note The next() method,whichisusedbytheothermethods,is protected so
that subclasses can change the generator implementation from that shown below
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed*multiplier+addend)&mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int) (nextseed >>> (48-bits));
}
to something different. For a subclassing example, check out “Subclassing
java.util.Random” ( http://www.javamex.com/tutorials/ran-
dom_numbers/java_util_random_subclassing.shtml ).
Because Random() does not take a seed argument, the resulting random number
generatoralwaysgeneratesadifferentsequenceofrandomnumbers.Thisexplainswhy
Search WWH ::




Custom Search