[java] Random Number Generation
I'm writing a program which needs to generate random numbers.
Math.random() returns a double between 0.0 and 1.0
#1.
I need to generate a random integer between 0 and n, with equal probability for each.
If I use
Math.random() * n
it means there is an infinitesimal chance of getting n (as the random function must evaluate to 1.0...very unlinkely)
so then I decided to use
(Math.random() * Integer.MAX_VALUE) % n
which will generate any integer between 0 and n, with reasonably equal probability...but not necessarily exactly (depending on the values of n and Integer.MAX_VALUE).
As it happens, I'm not too concerned with the evenness, but out of curiosity, if I NEEDED perfectly even distribution among the various values between 0 and n, how would I do it?
#2
I need to generate numbers, with different values having different probabilities of occuring.
I can think of no elegant way of doing it.
One way of doing it, is to construct an array, with each integer between 0 and n, occruing the number of times equal to its weight...
e.g.:
int[] bob = {0,0,0,1,2,3,3,3,3,4,5,5}
would give
0 weight: 3
1 weight: 1
2 weight: 1
3 weight: 4
4 weight: 1
5 weight: 2
and then generate a num between 0 and bob.length (as above), and use that to index the array, and thus generate a number between 0 and n, with the correct weightings.
is there a better way to do this?
#3
Anyone know where I can get a list of the relative frequenciy of occurance of each letter of the alphabet in english?
__________________
|