Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

java - Role of seed in random number generation

I have a big question in my mind:

I can use a seed number to generate random numbers:

Random rand = new Random(34666666);

But the thing that I cannot understand is the role of that seed. For example what is the difference of

That code with the following:

Random rand = new Random();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you supply a specific, hard-coded seed, to the one-arg Random constructor, the random numbers that will be generated will always be the same, every time you run the program. That is needed when you need a predictable source of random numbers.

However, when you don't supply a seed, then the Random constructor will choose a seed for you, based on System.nanoTime. The random numbers will be different every time you run the program, because the seed will be different each time.

Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

This is important because Java's random number generator is pseudo-random; each new pseudo-random number affects the seed that is used for the next pseudo-random number that gets generated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...