Java Reference
In-Depth Information
synchronized protected int next (int bits)
{
seed
=
(seed * 0x5DEECE66DL + 0xBL) & ((1L
<<
48) - 1);
return (int)(seed
>>>
(48 - bits));
}
Here the
mod
operation comes via the
AND
operation since
m
in this case has all
47 bits set to 1.
This method is
protected
(see Section 5.3.3, Access Rules). The public
random number methods accessible by all classes use the
next()
method. For
example,
nextInt()
simply includes the statement
return next (32);
The
nextLong()
method invokes
next(32)
, shifts the result by 32 bits to the
left, invokes
next(32)
again and then
OR
s the two values together to obtain a
64-bit random number:
return ((long)next (32)
<<
32) + next (32);
The
nextFloat()
method provides values in the range
0.0f
<=
x
<
1.0f
:
return next (24) / ((float)(1 << 24));
The
nextDouble()
method provides values in the range
0.0d
<=
x
<
1.0d
using the statement
return (((long)next (26)
<<
27) + next (27))/(double)(1L
<<
53)
The
nextBoolean()
method uses the statement
return next (1)!= 0;
See the
java.util.Random
class specification for more detailed descriptions
of the algorithms used for these and the other
next
Xxx
()
methods.
4.10 Improved histogram class
Here we make a subclass of the
BasicHist
class discussed in Chapter 3.
The class definition below shows that
BetterHist
inherits from
BasicHist
,
obtaining the properties of the latter while providing new capabilities.
Note how the constructor invokes
super()
to select a constructor in the base
class. Also, we see how the new methods in the subclass can access the data
variables in the base class. (In the next chapter we discuss access modifiers such
as
private
,which prevents subclasses from accessing a field or method.)
We add several methods to our histogram that provide various parameters
specifying the histogram. Also, a calculation of the mean and standard deviation
of the distribution in the histogram is included.
Search WWH ::
Custom Search