C# Random Question
I have two different realization random function:
Version 1:
public double myRnd()
{
Random rnd = new Random();
return rnd.NextDouble();
}
//-- Generate Random Number for Delaer
double DealersCard = myRnd();
//-- Generate Players 4 Random Number
double Box1Card = myRnd();
double Box2Card = myRnd();
double Box3Card = myRnd();
double Box4Card = myRnd();
version 2:
//开发者_如何学JAVA-- Create Random Object
var rnd = new Random();
//-- Generate Random Number for Delaer
double DealersCard = rnd.NextDouble();
//-- Generate Players 4 Random Number
double Box1Card = rnd.NextDouble();
double Box2Card = rnd.NextDouble();
double Box3Card = rnd.NextDouble();
double Box4Card = rnd.NextDouble();
Which method is better ?
Version 2 is much better. Version 1 is totally broken.
Version 1 recreates Random
for each number. Random
is seeded by Environment.TickCount
which changes only every 1-16ms. So you will get the same random number for all calls to myRnd
in that time interval.
In addition version 2 is faster since it doesn't need to recreate Random
.
Similar questions have been asked quite often, usually by people who implemented version 1 and wondered why it doesn't for. For example: Random number generator only generating one random number
The MSDN documentation for Random
states:
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.
http://msdn.microsoft.com/en-us/library/system.random.aspx
I've filed an improvement request on Microsoft Connect since this is a very common mistake.
The first one doesn't work very well.
The point in any random function is that it is pseudo-random, and the random value you get depends on the seed. When you create the Random
object, it is seeded with the current time.
So when you create a new Random
object every time you want a random number, you end up seeding with the current time again and again, which might result in getting the same numbers repeatedly (because the current time might not have changed, depending on the accuracy and resolution of the timer it uses).
The Random
class is used to create one object, from which you can get a sequence of random numbers.
精彩评论