Fast real valued random generator in java

后端 未结 6 1493
借酒劲吻你
借酒劲吻你 2020-12-31 12:51

java.util.Random.nextDouble() is slow for me and I need something really fast.

I did some google search and I\'ve found only integers based fast random generators.

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 13:33

    You could modify an integer based RNG to output doubles in the interval [0,1) in the following way:

    double randDouble = randInt()/(RAND_INT_MAX + 1.0)
    

    However, if randInt() generates a 32-bit integer this won't fill all the bits of the double because double has 53 mantissa bits. You could obviously generate two random integers to fill all mantissa bits. Or you could take a look at the source code of the Ramdom.nextDouble() implementation. It almost surely uses an integer RNG and simply converts the output to a double.

    As for performance, the best-performing random number generators are linear congruential generators. Of these, I recommend using the Numerical Recipes generator. You can see more information about LCGs from Wikipedia: http://en.wikipedia.org/wiki/Linear_congruential_generator

    However, if you want good randomness and performance is not that important, I think Mersenne Twister is the best choice. It also has a Wikipedia page: http://en.wikipedia.org/wiki/Mersenne_Twister

    There is a recent random number generator called PCG, explained in http://www.pcg-random.org/. This is essentially a post-processing step for LCG that improves the randomness of the LCG output. Note that PCG is slower than LCG because it is simply a post-processing step for LCG. Thus, if performance is very important and randomness quality not that important, you want to use LCG instead of PCG.

    Note that none of the generators I mentioned are cryptographically secure. If you need use the values for cryptographical applications, you should be using a cryptographically secure algorithm. However, I don't really believe that doubles would be used for cryptography.

提交回复
热议问题