Efficient way to generate lots of random numbers

2019-08-12 08:45发布

I have a java method that has to generate lots of random numbers in a very short period of time. My first approach was to use Math.random (which works really fast), but I have the presumption that because I call the Math.random so quick on behind the other, the "random" isn't really random (or less random) because of that (but I need it to be as random as possible).

I now have two questions:

  1. Is my presumption right, that because of the number of calls in a very short period of time the random output gets less random? And if the answer for 1. is Yes:
  2. What would be the fastest way (per call) to remove the problem with the less randomness?

I have already played around with the SecureRandom, but it is minimum 15 times slower than the normal Math.random, which is too slow for my requirements.

7条回答
劫难
2楼-- · 2019-08-12 09:46
  1. The (pseudo) random number generator produces the same results given the same initial seed values regardless of the frequency with which it is called. It is entirely deterministic and independent of speed. The selection of the seed is dependent on the time (if not explicitly specified), but not the sequence generated.
  2. If you need faster speed, you can pre-compute the values of a pseudo random number sequence larger than the length you need, and then use just one call to he generator to select a starting position in the sequence. This way, you can simply read out values after one initial call on all subsequent runs. Your performance will be limited by the speed at which you can index and read the memory holding the table. Depending on your application, potential reuse of the sequence may not be advisable.
查看更多
登录 后发表回答