Java Reference
In-Depth Information
ber that appears to be randomly chosen but is actually chosen by a predictable math
calculation, and hence is
pseudorandom
) is useful in simulations (as well as in games
andwhereveranelementofchanceisneeded).However,itsdoubleprecisionfloating-
pointrangeof0.0through(almost)1.0isn'tpractical.Tomake
random()
moreuseful,
its return value must be transformed into a more useful range, perhaps integer values
0through49,ormaybe-100through100.Youwillfindthefollowing
rnd()
method
useful for making these transformations:
static int rnd(int limit)
{
return (int) (Math.random()*limit);
}
rnd()
transforms
random()
's 0.0 to (almost) 1.0 double precision floating-point
rangetoa0through
limit
-1integerrange.Forexample,
rnd(50)
returnsaninteger
rangingfrom0through49.Also,
-100+rnd(201)
transforms0.0to(almost)1.0into
-100 through 100 by adding a suitable offset and passing an appropriate
limit
value.
Caution
Donotspecify
(int) Math.random()*limit
becausethisexpres-
sion always evaluates to 0. The expression first casts
random()
's double precision
floating-pointfractionalvalue(0.0through0.99999...)tointeger0bytruncatingthe
fractional part, and then multiplies 0 by
limit
, resulting in 0.
The
sin()
and
cos()
methodsimplementthesineandcosinetrigonometricfunc-
tions—see
http://en.wikipedia.org/wiki/Trigonomet-
ric_functions
.
These functions have uses ranging from the study of triangles
to modeling periodic phenomena (such as simple harmonic motion—see
ht-
4-1
presents the source code to an application that does just this.
Listing 4-1.
Graphing sine and cosine waves
class Graph
{
final static int ROWS = 11; // Must be odd
final static int COLS= 23;
public static void main(String[] args)
{