randomNumbers
Class RandomDist
java.lang.Object
randomNumbers.RandomDist
- public class RandomDist
- extends java.lang.Object
Demonstrates the difference in Random number distrobution using
Math.random() * n, Random.nextInt() % n and Random.nextInt(int n)
Given a randon number between a given range (0 to n) then if the distrobution
was random then we should be able to expect that roughly half the
numbers generated are in the range 0 to ((n/2)-1) whilst the rest are in the range n/2 to n-1.
However, the results of this program are:
Random number range is 0 to 1431655764
Using Math.random * n the number below 715827882 is 500714
Using Random.nextInt() % n the number below 715827882 is 666540
Using Random.nextInt(n) the number below 715827882 is 501091
This demonstrates a problem with using Random.nextInt() % n as there are
significantly more values below the halfway point than there should be!
Top Tip: always use Random.nextInt(n)
|
Field Summary |
private static java.util.Random |
rnd
|
|
Method Summary |
static void |
main(java.lang.String[] args)
main method - This is simply a functional program. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
rnd
private static java.util.Random rnd
RandomDist
public RandomDist()
main
public static void main(java.lang.String[] args)
- main method - This is simply a functional program.