C# Random generation

2020-02-15 06:16发布

I have just passed this article online: C# Corner and C# Corner and his article (a software developer with over 13 years of experience) recommended using System.Random as follows:

private int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max); 
}

Isn't that would give him the same number every time ??

Edit:
So my question will become: How does Random choose its seed? a constant or current time value?

Thanks

标签: c# random
4条回答
Root(大扎)
2楼-- · 2020-02-15 06:35

No because new Random() will init with current time as a seed. That said you should still preserve instance of the random and reuse it.

查看更多
smile是对你的礼貌
3楼-- · 2020-02-15 06:48

You should only initialize the seed once and then reuse it:

private Random random = new Random();

private int RandomNumber(int min, int max)
{
    return random.Next(min, max); 
}
查看更多
再贱就再见
4楼-- · 2020-02-15 06:53

Maybe. Random created without an explicit seed seeds itself based on current time. If you called RandomNumber rapidly enough you'd get the same number occasionally.

Your intuition is correct, however. It's dumb to create a new Random object every time you need a new number. You should create a single instance and use it.

查看更多
太酷不给撩
5楼-- · 2020-02-15 06:59

It will give the same result when the method will be called often between short time intervals. This is because the Randoms seed is initialized with the current time value. This is also the reason why many people have problem of kind that random is not random at all.

BTW it is not Math.Random but System.Random


Following your edit, here is some information on how random is initialized. The information comes from the link above.

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.

查看更多
登录 后发表回答