简体   繁体   中英

Generating random numbers with a vector of integers as seed in Java

I want to generate reproducible random numbers representing quantities at different points in 3 dimensional space, eg

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.

The Random class uses a 48-bit seed that's conveniently divided into three pieces of 16 bits in each, like so.

private static long createSeed(long x, long y, long z) {
    return (z & 0xffff) << 32 + (yy & 0xffff) << 16 + (x & 0xffff);
} 

How about

return new Random(seed ^ x ^ y ^ z).nextDouble();

(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 rnd = new Random(seed);
rnd.setSeed(rnd.nextLong() ^ x);
rnd.setSeed(rnd.nextLong() ^ y);
rnd.setSeed(rnd.nextLong() ^ z);
return rnd.nextDouble();

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:

 Random rand = new Random(seed+x+y+z);

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.

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 extend java.util.Random with a custom implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM