Java Reference

In-Depth Information

Nevertheless, the sequences of random numbers that are generated by Java

have been shown to have properties that truly random sequences of numbers

would have. They are “random enough” for people to use them with confidence

in their programs.

5.6.1

Method Math.random

Static function
Math.random()
can be used to generate a sequence of random

numbers. Whenever a new number is needed, call
Math.random()
again. It will

give you a different random number each time.

This function produces a
double
result
d
(say) in the range
0≤d<1
.

Suppose we want random values in the range
1..52
—for example, they

might be numbers of cards in a deck of cards. Thus, we need to convert a
dou-

ble
number
d
in the range
0≤d<1
into a value
k
in the range
1≤k≤52
. We

show how to do this. Start with:

0≤d<1

Multiply all three values by
52
:

0≤52*d<52

Cast the middle value to an
int
—this truncates toward 0:

0≤(
int
)(52 * d) < 52

Since the middle value is an integer, we have:

0≤(
int
)(52 * d) ≤ 51

Add 1 to each value:

1≤1+(
int
)(52*d) ≤ 52

So, we create and store in
k
a random integer in the range
1..52
using the assign-

ment:

k= 1 + (
int
)
(52*Math.random());

In the same way, the statements below store random numbers in the range

1..6
in two variables
die1
and
die2
, thus simulating the roll of a pair of dice:

die1= 1 + (
int
)
(6*Math.random());

die2= 1 + (
int
)
(6*Math.random());

5.6.2

Class Random

To gain more control over the generation of random numbers than is given by

Math.random
, use the methods of class
Random
, in package
java.util
. First,

create an instance of class
Random
, using one of its two constructors:

Search WWH ::

Custom Search