.NET源码中的随机数生成类

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;
    }

以上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值