'Generating random unique double values in Java

I need a collection of 64-bit floating point random numbers, and they should be distinct. Is there a library routine for this, or should I manually search for duplicates?

It is actually more important to have the numbers not being closer than some very small constant \epsilon. Is there a library routine for that as well?



Solution 1:[1]

You may use streams for that.

double[] array = new Random().doubles()
                             .distinct()
                             .limit(500) // How many you want.
                             .toArray();

Solution 2:[2]

You can use Set collection. It won't allow insertion of unique values. Below is an example:

Set<Double> doubles = new HashSet<Double>();
Random r = new Random();
for(int i=0 ; i<100 ; i++){
    doubles.add(r.nextDouble() * 100);
}

Solution 3:[3]

At first you need to understand, how a random-number-generator works. A sequence of positive integers, long integers, with no doubles in it, is calculated. This sequence is at least 2^31 elements long. The real doubles in the range of 0.0 ..... 1.0 are the result of a floating point division.Floating point division is never exact. If you use this real numbers to generate integer in smaller interval, it is the quickest method,to use a random-number-generator, which gives you positive integer from that interval. The algorithm for the Lehmer-generator is x1 = (x0 * m) % div x0 : the last random number,x1 the next random number. Div and m are prime numbers. m < div. The first x0 is select by the user.called seed number. It is clear, that the x_i are smaller then div. For the other properties of good random-number-generator, there is no short proof.

My suggestion: Write a method for a Lehmer-generator with m = 279470273 and div = 4294967291. I found these numbers on several web pages. Div = 2^32-5, so you can be sure to get a sequence of nearly 2^32 positive long integer,all different. Convert them to doubles and divide them with div as double. You get doubles in the open interval (0.0, ..... 1.0) and all these doubles are different. The random integers are small enough, that the quotients are also different. If you use a random generator, which generate bigger integer random numbers, you can not sure, that doubles are also different, the reason are rounding errors.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yassin Hajaj
Solution 2 Darshan Mehta
Solution 3