Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast real valued random generator in java

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. Is here anything for real numbers from interval <0, 1) ?

like image 549
Snurka Bill Avatar asked Mar 22 '15 10:03

Snurka Bill


People also ask

How do you generate a random number between 1000 and 9999 in Java?

int randomNumber = ( int )( Math. random() * 9999 ); if( randomNumber <= 1000 ) { randomNumber = randomNumber + 1000; Math. random() is a method that generates a random number through a formula.

How do you generate a random number from 1 to 10 in Java?

For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);


1 Answers

If you need something fast and have access to Java8, I can recommend the java.utils SplittableRandom. It is faster (~twice as fast) and has better statistical distribution.

If you need a even faster or better algorithm I can recommend one of these specialized XorShift variants:

  • XorShift128PlusRandom (faster & better)
  • XorShift1024StarPhiRandom (similar speed, even longer period)

Information on these algorithms and their quality can be found in this big PRNG comparison.

I made an independent Performance comparison you can find the detailed results and the code here: github.com/tobijdc/PRNG-Performance

TLDR

Never use java.util.Random, use java.util.SplittableRandom. If you need faster or better PRNG use a XorShift variant.

like image 163
tobijdc Avatar answered Oct 16 '22 18:10

tobijdc