生成大量随机数的有效方法 [英] Efficient way to generate lots of random numbers
问题描述
我有一个 java 方法,它必须在很短的时间内生成大量随机数.我的第一种方法是使用 Math.random(它工作得非常快),但我有一个假设,因为我在另一个之后调用 Math.random
如此快,随机"不是因此非常随机(或不那么随机)(但我需要它尽可能随机).
我现在有两个问题:
- 我的假设是否正确,因为在很短的时间内随机输出的随机性变小了?如果 1. 的答案是肯定的:
- 消除随机性较低的问题的最快方法(每次调用)是什么?
我已经尝试过 SecureRandom
,但它至少比普通 Math.random 慢 15 倍,这对于我的要求来说太慢了.
TL;DR:你的假设是错误的.
Math.random
作用于 java.util.Random
上的单个实例:
返回带正号的双精度值,大于或等于0.0 且小于 1.0.返回值是伪随机选择的,具有该范围内的(近似)均匀分布.
当这个方法首先被调用,它创建一个新的伪随机数生成器,就像表达式一样
new java.util.Random()
来自 JavaDoc
现在,java.util.Random
使用 线性同余公式"很可能与此构造函数的任何其他调用不同."1
由于这是一个伪随机级数 - 即它会从同一个种子中给出完全相同的值 - 您从 Math.random
中提取数字的速度对其随机性没有影响.>
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:
- 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:
- 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.
TL;DR: Your presumption is wrong.
Math.random
acts on a single instance on java.util.Random
:
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression
new java.util.Random()
From the JavaDoc
Now, java.util.Random
uses a linear congruential formula that is seeded with a number that is "very likely to be distinct from any other invocation of this constructor."1
As this is a pseudorandom progression - i.e. it will give exactly the same values from the same seed - the speed at which you extract numbers from Math.random
has no impact on their randomness.
这篇关于生成大量随机数的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!