Random Numbers

advertisement
Let’s not leave anything to chance
 How that process to generate random numbers takes
places requires some complicated statistics that are
outside the scope of this course. But there are a couple
of things to keep in mind:
1. The process focuses on creating a even distribution
of randomly chosen numbers.
2. The computer pulls a seed from somewhere to help
to randomize the process. It is sometimes the
previous random number chosen or the system time.
3. No number generated is ever truly random but they
come close enough.
 The most common way to obtain random numbers in
JAVA is to use the random method of the Math class.
 This method returns a number between zero and up to
but no including 1. So the method could return a .123,
0, .89, .5, .999999999 but it would never return a 1.
 You can change the range of numbers for
Math.random() by using a multiplier and an offset in
the following way:
 multiplier*Math.random() + offset
 So if you wanted to generate numbers between 300
and 400, you would use the following:
 101 * Math.random() + 300
 Note that the multiplier is 101 because it is 101 numbers
between 300 and 400 inclusively
 Math.random() returns a double.
 To obtain an integer, you can just cast the output as an
integer in the following manner:
 (int)(101 * Math.random() + 300)
 Do NOT do the following. It will result in a zero since
it casts the output of Math.random() as an int which
always produces a 0. Always cast after multiplying by
the multiplier.
 100 * (int)Math.random()
 JAVA also provides a Random Class which provides a
larger variety of options.
 Look at the API and Lesson 30 in Blue Pelican for more
details.
 It provides both a nextDouble() method which works
the same way as Math.random() as well as nextInt(n)
which returns a random int from 0 up to n-1
Download