What is the most efficent way to generate unique d

2019-03-07 05:47发布

问题:

There are methods such as searching for duplicates but I wonder if there is a better solution for this task.

回答1:

You may use streams for that.

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


回答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);
}


回答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.