best number as a seed for random class

2019-07-04 04:56发布

I want to generate random numbers between two integer numbers. In my case the numbers must meet some other conditions. I put generator.nextInt(x) in a loop and set seed again, if the new number doesn't meet my conditions.

The number which is generated is same in the number of loop iteration when I use System.currentTimeMillis() as seed. I replace System.currentTimeMillis() with System.nanoTime(). the result much better than previous one.

I want to know is there any better way for setting the seed?

标签: java random
3条回答
仙女界的扛把子
2楼-- · 2019-07-04 05:22

If you repeatedly use System.currentTimeMillis() it won't actually be changing that often. i.e. once per milli-second at best. If you use System.nanoTime() it can change every micro-second or better.

I suspect you don't need to reset the seed as the sequence is supposed to be random. Just keep picking random numbers instead.

查看更多
beautiful°
3楼-- · 2019-07-04 05:25

You don't need to seed again. Everytime you do the generator.nexInt(x) you get a new random number, that is

0 <= random_number < x.

查看更多
你好瞎i
4楼-- · 2019-07-04 05:31

You can use the constructor for Random that doesn't take a parameter. That constructor initializes its seed based on System.nanoTime() already. Every time you invoke that constructor the seed will be different.

Generally you would only seed Random yourself when you want a repeatable sequence of random data (they are determinstic).

Either way, you can always keep calling nextInt (or any nextXyz method) and keep getting more random numbers without having to re-seed for every number.

Random numbers in Java are pseudo-random. They need a seed that is used to generate the next random number.

查看更多
登录 后发表回答