C# Random Seed Value of int.MinValue Unpredictable
因此,我目前正在尝试测试使用随机函数的函数。为了测试它,我将种子值传递给C#Random函数。 (即System.Random)
我的测试用例涉及使用int.MaxValue和int.MinValue进行边界测试。整数的最大值产生一致且预期的结果。但是当我尝试使用最小值时,下一个将继续产生无法预测的随机结果,因此无法进行测试。
我很好奇这是预期的还是种子无法产生可预测结果的原因。我错过了什么吗?
预先感谢。
编辑:
提供代码以供参考。这些方法是我使用的数组扩展,用于将数组随机排列。我正在使用随机类以获取各种结果,并将我的种子作为可选参数传入以进行测试。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | public static void Shuffle< T >(this T[] array, int seedValue = -1) { // Create the randomizer that will be needed Random random = seedValue >= 0 ? new Random(seedValue) : new Random(); // Run the algorithm for (int i = array.Length - 1; i > 0; i--) { // Get a random integer with a maximum of i int r = random.Next(i); // Swap the element at r with the element at i array.Swap(r, i); } } public static void Swap< T >(this T[] array, int indexOne, int indexTwo) { // Check if the indices that we were passed are the same index if (indexOne == indexTwo) { return; } // Check that the first index is in range if (indexOne < 0 || indexOne >= array.Length) { throw new ArgumentOutOfRangeException("indexOne","The first index provided is out of the range of the array provided."); } // Check that the second index is in range if (indexTwo < 0 || indexTwo >= array.Length) { throw new ArgumentOutOfRangeException("indexTwo","The second index provided is out of the range of the array provided."); } // Swap the items T temp = array[indexOne]; array[indexOne] = array[indexTwo]; array[indexTwo] = temp; } |
这些就是正在测试的方法。我正在将minvalue传递给Shuffle函数。经过我自己的进一步调查,它似乎正在以任何负面价值发生。似乎产生不一致的结果。我目前正在使用.NET 2.0。我知道旧版本,但是我正在Unity内部工作。
这是您的问题:
如果您传递的种子值小于零,则根本就没有使用它,
很自然地,随机种子是从正在运行的计算机时钟中选择的。
如果检查
1 2 | int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs( Seed ); |
此检查意味着,如果