两种不同的种子产生相同的“随机”序列

也许对此有一个非常逻辑的解释,但我似乎无法理解为什么种子02,147,483,647使用.NET的随机类(系统)产生相同的“随机”序列。

快速代码示例:

 var random1 = new Random(0); var random2 = new Random(1); var random3 = new Random(int.MaxValue); //2,147,483,647 var buffer1 = new byte[8]; var buffer2 = new byte[8]; var buffer3 = new byte[8]; random1.NextBytes(buffer1); random2.NextBytes(buffer2); random3.NextBytes(buffer3); for (int i = 0; i < 8; i++) { Console.WriteLine("{0}\t\t{1}\t\t{2}", buffer1[i], buffer2[i], buffer3[i]); } 

输出:

 26 70 26 12 208 12 70 134 76 111 130 111 93 64 93 117 151 115 228 228 228 216 163 216 

如您所见,第一个和第三个序列是相同的。 有人可以向我解释一下吗?

编辑 :显然,正如alro所指出的,这些序列并不相同。 但它们非常相似。

那么,原因将与Random类使用的任何派生函数相关联,以从种子中导出伪随机序列。 因此, 真正的答案是数学(超出我的能力)。

确实 – 我不相信有任何保证两种不同的种子必然会产生不同的序列。

编辑好的 – 我将做bitbonk所做的事 – 但解释原因

 public Random(int Seed) { int num = (Seed == -2147483648) ? 2147483647 : Math.Abs(Seed); int num2 = 161803398 - num; this.SeedArray[55] = num2; int num3 = 1; for (int i = 1; i < 55; i++) { int num4 = 21 * i % 55; this.SeedArray[num4] = num3; num3 = num2 - num3; if (num3 < 0) { num3 += 2147483647; } num2 = this.SeedArray[num4]; } for (int j = 1; j < 5; j++) { for (int k = 1; k < 56; k++) { this.SeedArray[k] -= this.SeedArray[1 + (k + 30) % 55]; if (this.SeedArray[k] < 0) { this.SeedArray[k] += 2147483647; } } } this.inext = 0; this.inextp = 21; Seed = 1; } 

我们实际上并不需要深入到代码中来查看原因 - 从上到下读取代码这些是当种子为0且种子为2147483647时由上述代码存储的值:

 int num = (Seed == -2147483648) ? 2147483647 : Math.Abs(Seed); => num is 0 and 2147483647 int num2 = 161803398 - num; => num2 is 161803398 and -1985680249 this.SeedArray[55] = num2; => this.SeedArray is as above in both cases int num3 = 1; for (int i = 1; i < 55; i++) { int num4 = 21 * i % 55 this.SeedArray[num4] = num3; => num4 is 21, SeedArray[21] is 1 num3 = num2 - num3 => num3 is 161803397 and -1985680250 if(num3 < 0) num3 += 2147483647 => num3 is 161803397 and 161803397 

在第一个循环之后,算法已经收敛了两个种子值。

编辑

正如在问题上指出的那样 - 序列不一样 - 但它们显然非常相似 - 在这里我们可以看到这种相似性的原因。