简体   繁体   中英

C# Random number unique first number

If I create a Random() with a different starting seed every time will the first number in the generator be unique every time, or is there a point in which the first number will start repeating?

Example:

var random1 = new Random(1);
var value1 = random1.Next();
var random2 = new Random(2);
var value2 = random2.Next();
var random3 = new Random(x);
var value3 = random3.Next();

where value1 != value2 != value3;

EDIT: Fixed variable names I have tested seeds of 0-80,000,000, I am just wondering if they are unique from 0-int.Max, or if the first 80,000,000 are unique by accident

Generally, I don't think there is any requirement that pseudorandom generators should generate unique numbers given unique seeds.

The only think it happens is that, given a seed, the generator will always generate the same number sequence (obtained by calling multiple times the next method) and the sequence will repeat at some point. However, the C# Random class uses a subtractive generation algorithm, where the next random number is generated basing on previous numbers of the sequence. Hence, there may be some kind of dependency between the number and the seed, which makes the random number generator to generate unique numbers every time the seed is changed.

If you want to be sure, either try it yourself with seeds from int.MinValue to int.MaxValue , or check the C# implementation here https://referencesource.microsoft.com/#mscorlib/system/random.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM