1000 Java Tips ebook
Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!.
Java: Random numbers - intro
JavaFAQ Home » Java Notes by Fred Swartz
When to use random numbers
There are many types of programs that use random numbers.
Game programs use them to create situations that are
not always the same every time a player is in the same situation,
or maybe you want to program to shuffle a deck of cards.
Simulations usually use random numbers.
You might want to use random numbers to change the
appearance of something -- screensavers are an
example of use. There are many other uses also.
Type, Range, and Distribution
When you generate random numbers, you need to decide
which type you need (eg, int or double), what range
you need (minimum to maximum), and how they are
distributed. There are two common types of distributions:
uniform and normal (equivalent to Gaussian).
In a uniform distribution all numbers in the range are
equally likely to be produced.
How can a computer generate a random number?
Computers are deterministic -- they do the same thing whenever
they have the same input. Therefore, in some way it is
impossible for a computer to compute a truly random number.
But the methods that are used generate sequences of numbers
that meet the statistical requirements of randomness.
Because the numbers are not truly random, they are
sometimes referred to as pseudorandom numbers.
These random number generates will produce exactly the same
sequence of pseudorandom numbers if they start with the
same initial value. This initial value is called the seed.
If we start a program with the same random seed, we
will get the same sequence of numbers.
The default seed is the current time in milliseconds since 1970.
This works very well, but there are two issues.
- You may want to set the seed so that the sequence
can be reproduced when you are testing your program.
- If you want more than one random sequence, you should
use only one random generater because, if two
random generators are created during initialization,
it is very likely that they are created in the same
millisecond, which means they have the same seed,
and will produce the same sequence of "random" values.
Math.random uses only one seed, so it
is safe for this even if it has less convenient
methods than the
Excursion 1: Random Thoughts by Joshua Bloch, author of Effective Java.
Printer Friendly Page
Send to a Friend
Search here again if you need more info!