4 Replies Latest reply on Jan 15, 2013 8:27 PM by morgalr

Generaterandom numbers with equal probability

I wanna to generate numbers -in range- with equal probability*.
So I have minimum value and maximum value and number of generate numbers and return array of numbers, like this:
``````public long[] doGenerate(int min, int max, int total)
{
long ret=new long[total];
//
// here the code what I want
//
return ret[];
}``````
Thank you.
• 1. Re: Generaterandom numbers with equal probability
Start by reading the documentation of java.util.Random. It also talks about SecureRandom, which, depending on your application, may be what you need.
Question: why the return is an array of longs, while the arguments min and max are ints?
• 2. Re: Generaterandom numbers with equal probability
I'm using long array to more accurate values, if I want to read all java.util.Random so I don't need to put my question here!!

I want to tutorial or example or solution :(
• 3. Re: Generaterandom numbers with equal probability
I'm using long array to more accurate values
The range is specified in ints, and you are storing whole numbers, so this remark doesn't make any sense. Using a long for a value that fits into an int doesn't add precision, it just wastes space.
if I want to read all java.util.Random so I don't need to put my question here!!
Exactly. So what's the problem?
I want to tutorial or example or solution
And you've been told where to find it.
• 4. Re: Generaterandom numbers with equal probability
981815 wrote:
I wanna to generate numbers -in range- with equal probability*.
First off, there is no such thing as random numbers with equal probability--all random numbers in the computer world are called pseudo random numbers because they are all generated and follow a patter set forth by their algorithm. They will all have peeks and valleys in their distribution, but the best of them are near equal over extreamly long test cases. That does not mean that you couldn't ask for a random number and get a number, say 5, back 1000 times in a row; it's not very probable, but it could happen.

As stated in previos posts, the Random Class is what you are looking for, it you are not motivated enough to study it over, then you really do not need a solution that bad.

It appears that you are looking for whole numbers: you can guarentee that you do not get a repeat from your custom programmed random number method by hashing to the next open number in your range. You'll have to track each number as it is given from he Random object and hash to the next open if it has already been used.