在 Java 中以整数向量作为种子生成随机数
我想生成可重复的随机数来表示 3 维空间中不同点的数量,例如
double draw = rand(int seed, int x, int y, int z)
我希望相同的输入始终产生相同的绘图。我不想提前生成所有值,因为数量太多。
我希望不同位置的抽签是独立的。我还希望不同种子的相同位置的抽签是独立的。这排除了取四个参数的总和或乘积,并将其用作种子。
I want to generate reproducible random numbers representing quantities at different points in 3 dimensional space, e.g.
double draw = rand(int seed, int x, int y, int z)
I want the same inputs to always produce the same draw. I don’t want to generate all the values in advance as there would be too many.
I want the draws for different positions to be independent. I also want draws for the same position with different seeds to be independent. This rules out taking the sum or product of the four arguments, and using this as a seed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样
(因为构造函数的种子参数实际上是 64 位,你可以通过在 xor:ing 之前将两个整数上移 32 位来获得更好的“传播”)
另一个简单的解决方案是执行类似的操作
How about
(since the seed-argument to the constructor is actually 64 bits, you could get a better "spread" by, say shifting up two of your ints by 32 bits before xor:ing)
Another simple solution would be to do something like
Random 类使用 48 位种子它可以方便地分为三部分,每部分 16 位,如下所示。
The Random class uses a 48-bit seed that's conveniently divided into three pieces of 16 bits in each, like so.
Java 有 随机(长种子)< /a> 构造函数,但它只需要一个 long 值。
但您不必太担心,因为您可以对向量和种子应用(数学)函数来生成单个数字。穷人的版本只是将数字相加:
但正如您自己可能注意到的那样,这不是最好的版本,因为它对 (1,0,0) 和 (0,1,0) 和 (0 ,0,1)。我相信您可以想出一个更好的函数,例如
seed + 31*31*x + 31*y + z
或类似函数。Java has Random(long seed) constructor but it takes only a single long value.
But you shouldn't worry much since you can apply a (mathematical) function to your vector and your seed to produce a single number. A poor man's version would be simply adding the numbers:
But as you probably noticed yourself, that isn't the best one as it yields the same result for (1,0,0) and (0,1,0) and (0,0,1). I am sure you can think up a better function instead like
seed + 31*31*x + 31*y + z
or similar.如
中所述setSeed()
API,java.util.Random
使用 48 位种子。您的模型可能会建议定义一个合适的函数来散列您的三个整数。或者,您可以使用自定义实现来扩展java.util.Random
。As noted in the
setSeed()
API,java.util.Random
uses a 48-bit seed. Your model may suggest the definition of a suitable function to hash your three integer's. Alternatively, you can extendjava.util.Random
with a custom implementation.