View Single Post
Old 02-21-2004, 12:05 PM   #1 (permalink)
CSflim
Sky Piercer
 
CSflim's Avatar
 
Location: Ireland
[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?
__________________
CSflim is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73