02-21-2004, 12:05 PM | #1 (permalink) |
Sky Piercer
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?
__________________
|
02-21-2004, 11:40 PM | #2 (permalink) |
Crazy
|
for the first, import java.util.Random;
Random gen = new Random(); gen.NextInt(n+1); gen is merely the name of the random generator, I use gen, call it whatever you want. *edit* sorry, you know that I'm sure, it's just a constructor. Didnt mean to insult your intelligence. for the second, generate a random number between say 1 and 100, then use if statements, if its between 1 and 30, its 1, 31-40 its 2, etc. gives one a 30% chance, 2 a tne percent chance. That is the only way I can think of, I don't know whether it would be any easier. for the third, perhaps this will help: http://www.askoxford.com/asktheexper...ords/frequency Last edited by bellzboy; 02-21-2004 at 11:42 PM.. |
Tags |
generation, java, number, random |
|
|