Random类,微软对其的描述如下:
Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness.
表示一个伪随机数生成器,满足某种统计学上的要求的随机性。
类的数据结构定义如下:
public class Random
{
private int[] SeedArray = new int[56];
private int inext;
private int inextp;
private const int MBIG = 2147483647;
private const int MSEED = 161803398;
private const int MZ = 0;
而构造函数的实现如下:需要传入一个随机种子,以便构造SeedArray。
public Random(int Seed)
{
int num1 = 161803398 - (Seed == int.MinValue ? int.MaxValue : Math.Abs(Seed));
this.SeedArray[55] = num1;
int num2 = 1;
for (int index1 = 1; index1 < 55; ++index1)
{
int index2 = 21 * index1 % 55;
this.SeedArray[index2] = num2;
num2 = num1 - num2;
if (num2 < 0)
num2 += int.MaxValue;
num1 = this.SeedArray[index2];
}
for (int index1 = 1; index1 < 5; ++index1)
{
for (int index2 = 1; index2 < 56; ++index2)
{
this.SeedArray[index2] -= this.SeedArray[1 + (index2 + 30) % 55];
if (this.SeedArray[index2] < 0)
this.SeedArray[index2] += int.MaxValue;
}
}
this.inext = 0;
this.inextp = 21;
Seed = 1;
}
而生成一个随机int32型的整数的实现如下:
public virtual int Next(int maxValue)
{
if (maxValue >= 0)
return (int) (this.Sample() * (double) maxValue);
throw new ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", new object[1]
{
(object) "maxValue"
}));
}
取样函数Sample()的实现如下:
protected virtual double Sample()
{
return (double) this.InternalSample() * 4.6566128752458E-10;
}
private int InternalSample()
{
int num1 = this.inext;
int num2 = this.inextp;
int index1;
if ((index1 = num1 + 1) >= 56)
index1 = 1;
int index2;
if ((index2 = num2 + 1) >= 56)
index2 = 1;
int num3 = this.SeedArray[index1] - this.SeedArray[index2];
if (num3 == int.MaxValue)
--num3;
if (num3 < 0)
num3 += int.MaxValue;
this.SeedArray[index1] = num3;
this.inext = index1;
this.inextp = index2;
return num3;
}
以上。