C#的Random类的源码

Code:
  1. C#的Random类的源码    
  2. // ==++==   
  3. //    
  4. //      
  5. //    Copyright (c) 2002 Microsoft Corporation.  All rights reserved.   
  6. //      
  7. //    The use and distribution terms for this software are contained in the file   
  8. //    named license.txt, which can be found in the root of this distribution.   
  9. //    By using this software in any fashion, you are agreeing to be bound by the   
  10. //    terms of this license.   
  11. //      
  12. //    You must not remove this notice, or any other, from this software.   
  13. //      
  14. //    
  15. // ==--==   
  16. /**//*-------------------------------------  
  17. **  
  18. ** Class:  Random.cs  
  19. **  
  20. **                                          
  21. **  
  22. ** Purpose: A random number generator.  
  23. **  
  24. ** Date:  July 8, 1998  
  25. **   
  26. --------------------------------------------*/  
  27. namespace System {   
  28.        
  29.     using System;   
  30.     using System.Runtime.CompilerServices;   
  31.     /**//// <include file='doc/Random.uex' path='docs/doc[@for="Random"]/*' />   
  32.     [Serializable()] public class Random {   
  33.       //   
  34.       // Private Constants    
  35.       //   
  36.       private const int MBIG =  Int32.MaxValue;   
  37.       private const int MSEED = 161803398;   
  38.       private const int MZ = 0;   
  39.        
  40.       //   
  41.       // Member Variables   
  42.       //   
  43.       private int inext, inextp;   
  44.       private int[] SeedArray = new int[56];   
  45.        
  46.       //   
  47.       // Public Constants   
  48.       //   
  49.        
  50.       //   
  51.       // Native Declarations   
  52.       //   
  53.        
  54.       //   
  55.       // Constructors   
  56.       //   
  57.        
  58.       /** <include file='doc/Random.uex' path='docs/doc[@for="Random.Random"]/*' />   
  59.       public Random()    
  60.         : this(Environment.TickCount) {   
  61.       }   
  62.        
  63.       /** <include file='doc/Random.uex' path='docs/doc[@for="Random.Random1"]/*' />   
  64.       public Random(int Seed) {   
  65.         int ii;   
  66.         int mj, mk;   
  67.        
  68.         //Initialize our Seed array.   
  69.         //This algorithm comes from Numerical Recipes in C (2nd Ed.)   
  70.         mj = MSEED - Math.Abs(Seed);   
  71.         SeedArray[55]=mj;   
  72.         mk=1;   
  73.         for (int i=1; i<55; i++) {  //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.   
  74.           ii = (21*i)%55;   
  75.           SeedArray[ii]=mk;   
  76.           mk = mj - mk;   
  77.           if (mk<0) mk+=MBIG;   
  78.           mj=SeedArray[ii];   
  79.         }   
  80.         for (int k=1; k<5; k++) {   
  81.           for (int i=1; i<56; i++) {   
  82.         SeedArray[i] -= SeedArray[1+(i+30)%55];   
  83.         if (SeedArray[i]<0) SeedArray[i]+=MBIG;   
  84.           }   
  85.         }   
  86.         inext=0;   
  87.         inextp = 21;   
  88.         Seed = 1;   
  89.       }   
  90.        
  91.       //   
  92.       // Package Private Methods   
  93.       //   
  94.        
  95.       /**//*====================================Sample====================================   
  96.       **Action: Return a new random number [0..1) and reSeed the Seed array.   
  97.       **Returns: A double [0..1)   
  98.       **Arguments: None   
  99.       **Exceptions: None   
  100.       ==============================================================================*/   
  101.       /**//// <include file='doc/Random.uex' path='docs/doc[@for="Random.Sample"]/*' />   
  102.       protected virtual double Sample() {   
  103.           int retVal;   
  104.           int locINext = inext;   
  105.           int locINextp = inextp;   
  106.   
  107.           if (++locINext >=56) locINext=1;   
  108.           if (++locINextp>= 56) locINextp = 1;   
  109.              
  110.           retVal = SeedArray[locINext]-SeedArray[locINextp];   
  111.              
  112.           if (retVal<0) retVal+=MBIG;   
  113.              
  114.           SeedArray[locINext]=retVal;   
  115.   
  116.           inext = locINext;   
  117.           inextp = locINextp;   
  118.                        
  119.           //Including this division at the end gives us significantly improved   
  120.           //random number distribution.   
  121.           return (retVal*(1.0/MBIG));   
  122.       }   
  123.        
  124.       //   
  125.       // Public Instance Methods   
  126.       //    
  127.        
  128.        
  129.       /**//*=====================================Next=====================================   
  130.       **Returns: An int [0.._int4.MaxValue)   
  131.       **Arguments: None   
  132.       **Exceptions: None.   
  133.       ==============================================================================*/   
  134.       /**//// <include file='doc/Random.uex' path='docs/doc[@for="Random.Next"]/*' />   
  135.       public virtual int Next() {   
  136.         return (int)(Sample()*Int32.MaxValue);   
  137.       }   
  138.        
  139.       /**//*=====================================Next=====================================   
  140.       **Returns: An int [minvalue..maxvalue)   
  141.       **Arguments: minValue -- the least legal value for the Random number.   
  142.       **           maxValue -- the greatest legal return value.   
  143.       **Exceptions: None.   
  144.       ==============================================================================*/   
  145.       /**//// <include file='doc/Random.uex' path='docs/doc[@for="Random.Next1"]/*' />   
  146.       public virtual int Next(int minValue, int maxValue) {   
  147.           if (minValue>maxValue) {   
  148.               throw new ArgumentOutOfRangeException("minValue",String.Format(Environment.GetResourceString("Argument_MinMaxValue"), "minValue""maxValue"));   
  149.           }   
  150.              
  151.           int range = (maxValue-minValue);   
  152.        
  153.           //This is the case where we flipped around (e.g. MaxValue-MinValue);   
  154.           if (range<0) {   
  155.               long longRange = (long)maxValue-(long)minValue;   
  156.               return (int)(((long)(Sample()*((double)longRange)))+minValue);   
  157.           }   
  158.              
  159.           return ((int)(Sample()*(range)))+minValue;   
  160.       }   
  161.        
  162.        
  163.       /**//*=====================================Next=======================   
  164.       **Returns: An int [0..maxValue)   
  165.       **Arguments: maxValue -- the greatest legal return value.   
  166.       **Exceptions: None.   
  167. ======================================================================*/   
  168.       /**//// <include file='doc/Random.uex' path='docs/doc[@for="Random.Next2"]/*' />   
  169.       public virtual int Next(int maxValue) {   
  170.           if (maxValue<0) {   
  171.               throw new ArgumentOutOfRangeException("maxValue", String.Format(Environment.GetResourceString("ArgumentOutOfRange_MustBePositive"), "maxValue"));   
  172.           }   
  173.           return (int)(Sample()*maxValue);   
  174.       }   
  175.        
  176.        
  177.       /**//*=====================================Next=======================   
  178.       **Returns: A double [0..1)   
  179.       **Arguments: None   
  180.       **Exceptions: None   
  181.       ======================================================================*/   
  182.       /**//// <include file='doc/Random.uex' path='docs/doc[@for="Random.NextDouble"]/*' />   
  183.       public virtual double NextDouble() {   
  184.         return Sample();   
  185.       }   
  186.        
  187.        
  188.       /**//*==================================NextBytes=====================   
  189.       **Action:  Fills the byte array with random bytes [0..0x7f].  The entire array is filled.   
  190.       **Returns:Void   
  191.       **Arugments:  buffer -- the array to be filled.   
  192.       **Exceptions: None   
  193.       ======================================================================*/   
  194.       /**//// <include file='doc/Random.uex' path='docs/doc[@for="Random.NextBytes"]/*' />   
  195.       public virtual void NextBytes(byte [] buffer){   
  196.         if (buffer==nullthrow new ArgumentNullException("buffer");   
  197.         for (int i=0; i<buffer.Length; i++) {   
  198.           buffer[i]=(byte)(Sample()*(Byte.MaxValue+1));    
  199.         }   
  200.       }   
  201.     }   
  202. }   

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值