Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is random seed about?

Tags:

java

random

seed

For example the code below. It has a random class. However it always produce the same output everywhere . In this case which item is the seed?

source: link

import java.util.Random;
public class RandomTest {
    public static void main(String[] s) {
        Random rnd1 = new Random(42);
        Random rnd2 = new Random(42);

        System.out.println(rnd1.nextInt(100)+" - "+rnd2.nextInt(100));
        System.out.println(rnd1.nextInt()+" - "+rnd2.nextInt());
        System.out.println(rnd1.nextDouble()+" - "+rnd2.nextDouble());
        System.out.println(rnd1.nextLong()+" - "+rnd2.nextLong());
    }
}
like image 315
newbieprogrammer Avatar asked Dec 06 '22 02:12

newbieprogrammer


2 Answers

42 is the seed, as the very same Javadoc says. So, what is a seed? A random number is seldom truly random - often it's a pseudo-random instead. This means it's generated from a function, which is said PRNG (pseudo random number genrator). Being generated from a function, in turn, means that the output is not random anymore, since it's predictable!

However, depending on your needs, this pseudo-randomness may be enough - I said enough because generating random bit is expensive, and I'm not talking about time or memory, but about money (see this link on wikipedia). So, for example, if you need a random value to place enemies in your game, a pseudo-random number is ok - but if your are building security-related software, you want to use a true random number, or at least a cryptographically secure PRNG.

How can we describe a PRNG, like the one used in Math.random()? It's a function, initialized with a seed S that returns an array of values A. Note that, for each integer S, is defined one and only one array A. For example (values are not actual):

                first call     second call     third call
seed: 14329            .18             .82             .5
seed:  3989             .7             .02            .93

So you seed you PRNG with some known value when you want its result to be predictable - for example for testing purposes or to ensure that, each time you run level 1 in your game, the enemies are always placed in the same (pseudo) random places - otherwise you don't need to explicitely pass a seed.

like image 197
Raffaele Avatar answered Dec 08 '22 14:12

Raffaele


Random Seed on Wikipedia:

A random seed (or seed state, or just seed) is a number (or vector) used to initialize a pseudorandom number generator.

In other word, it is the number from which a seem-to-be-random sequence will be generated. Therefore, if you use the same number, the senquence will always be the same.

In practice, we usually use System Time as seed.

like image 31
Luke Vo Avatar answered Dec 08 '22 14:12

Luke Vo