What is the most efficent way to generate unique double values in Java

后端 未结 3 1198
温柔的废话
温柔的废话 2021-01-29 14:47

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

相关标签:
3条回答
  • 2021-01-29 15:12

    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);
    }
    
    0 讨论(0)
  • 2021-01-29 15:15

    You may use streams for that.

    double[] array = new Random().doubles()
                                 .distinct()
                                 .limit(500) // How many you want.
                                 .toArray();
    
    0 讨论(0)
  • 2021-01-29 15:22

    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.

    0 讨论(0)
提交回复
热议问题