Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RefactorPluginInfrastructure-2522/HeuristicLab.ExtLibs/HeuristicLab.SimSharp/3.0.7/SimSharp-3.0.7/Random/FastRandom.cs @ 13332

Last change on this file since 13332 was 12657, checked in by abeham, 9 years ago

#2420: Added Sim# as an ExtLib plugin

File size: 17.7 KB
Line 
1/* ***************************************************************************
2 * This file is part of SharpNEAT - Evolution of Neural Networks.
3 *
4 * Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
5 *
6 * SharpNEAT is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * SharpNEAT is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with SharpNEAT.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20// ENHANCEMENT: Replace usages of this class with the superceding version from Math.Net.
21using System;
22
23namespace SimSharp {
24  /// <summary>
25  /// A fast random number generator for .NET
26  /// Colin Green, January 2005
27  ///
28  /// Key points:
29  ///  1) Based on a simple and fast xor-shift pseudo random number generator (RNG) specified in:
30  ///  Marsaglia, George. (2003). Xorshift RNGs.
31  ///  http://www.jstatsoft.org/v08/i14/paper
32  /// 
33  ///  This particular implementation of xorshift has a period of 2^128-1. See the above paper to see
34  ///  how this can be easily extened if you need a longer period. At the time of writing I could find no
35  ///  information on the period of System.Random for comparison.
36  ///
37  ///  2) Faster than System.Random. Up to 8x faster, depending on which methods are called.
38  ///
39  ///  3) Direct replacement for System.Random. This class implements all of the methods that System.Random
40  ///  does plus some additional methods. The like named methods are functionally equivalent.
41  /// 
42  ///  4) Allows fast re-initialisation with a seed, unlike System.Random which accepts a seed at construction
43  ///  time which then executes a relatively expensive initialisation routine. This provides a vast speed improvement
44  ///  if you need to reset the pseudo-random number sequence many times, e.g. if you want to re-generate the same
45  ///  sequence of random numbers many times. An alternative might be to cache random numbers in an array, but that
46  ///  approach is limited by memory capacity and the fact that you may also want a large number of different sequences
47  ///  cached. Each sequence can be represented by a single seed value (int) when using FastRandom.
48  /// 
49  ///  Notes.
50  ///  A further performance improvement can be obtained by declaring local variables as static, thus avoiding
51  ///  re-allocation of variables on each call. However care should be taken if multiple instances of
52  ///  FastRandom are in use or if being used in a multi-threaded environment.
53  ///
54  ///
55  /// Colin Green, September 4th 2005
56  ///   - Added NextBytesUnsafe() - commented out by default.
57  ///   - Fixed bug in Reinitialise() - y,z and w variables were not being reset.
58  ///     
59  /// Colin Green, December 2008.
60  ///   - Fix to Next() - Was previously able to return int.MaxValue, contrary to the method's contract and comments.
61  ///   - Modified NextBool() to use _bitMask instead of a count of remaining bits. Also reset the bit buffer in Reinitialise().
62  ///   
63  /// Colin Green, 2011-08-31
64  ///   - Added NextByte() method.
65  ///   - Added new statically declared seedRng FastRandom to allow easy creation of multiple FastRandoms with different seeds
66  ///     within a single clock tick.
67  ///     
68  /// Colin Green, 2011-10-04
69  ///  - Seeds are now hashed. Without this the first random sample for nearby seeds (1,2,3, etc.) are very similar
70  ///    (have a similar bit pattern). Thanks to Francois Guibert for identifying this problem.
71  ///
72  /// </summary>
73  public class FastRandom : IRandom {
74    #region Static Fields
75    /// <summary>
76    /// A static RNG that is used to generate seed values when constructing new instances of FastRandom.
77    /// This overcomes the problem whereby multiple FastRandom instances are instantiated within the same
78    /// tick count and thus obtain the same seed, that approach can result in extreme biases occuring
79    /// in some cases depending on how the RNG is used.
80    /// </summary>
81    static readonly FastRandom __seedRng = new FastRandom((int)System.Environment.TickCount);
82    #endregion
83
84    #region Instance Fields
85
86    // The +1 ensures NextDouble doesn't generate 1.0
87    const double REAL_UNIT_INT = 1.0 / ((double)int.MaxValue + 1.0);
88    const double REAL_UNIT_UINT = 1.0 / ((double)uint.MaxValue + 1.0);
89    const uint Y = 842502087, Z = 3579807591, W = 273326509;
90
91    uint _x, _y, _z, _w;
92
93    #endregion
94
95    #region Constructors
96
97    /// <summary>
98    /// Initialises a new instance using a seed generated from the class's static seed RNG.
99    /// </summary>
100    public FastRandom() {
101      Reinitialise(__seedRng.NextInt());
102    }
103
104    /// <summary>
105    /// Initialises a new instance using an int value as seed.
106    /// This constructor signature is provided to maintain compatibility with
107    /// System.Random
108    /// </summary>
109    public FastRandom(int seed) {
110      Reinitialise(seed);
111    }
112
113    #endregion
114
115    #region Public Methods [Reinitialisation]
116
117    /// <summary>
118    /// Reinitialises using an int value as a seed.
119    /// </summary>
120    public void Reinitialise(int seed) {
121      // The only stipulation stated for the xorshift RNG is that at least one of
122      // the seeds x,y,z,w is non-zero. We fulfill that requirement by only allowing
123      // resetting of the x seed.
124
125      // The first random sample will be very closely related to the value of _x we set here.
126      // Thus setting _x = seed will result in a close correlation between the bit patterns of the seed and
127      // the first random sample, therefore if the seed has a pattern (e.g. 1,2,3) then there will also be
128      // a recognisable pattern across the first random samples.
129      //
130      // Such a strong correlation between the seed and the first random sample is an undesirable
131      // charactersitic of a RNG, therefore we significantly weaken any correlation by hashing the seed's bits.
132      // This is achieved by multiplying the seed with four large primes each with bits distributed over the
133      // full length of a 32bit value, finally adding the results to give _x.
134      _x = (uint)((seed * 1431655781)
135                  + (seed * 1183186591)
136                  + (seed * 622729787)
137                  + (seed * 338294347));
138
139      _y = Y;
140      _z = Z;
141      _w = W;
142
143      _bitBuffer = 0;
144      _bitMask = 1;
145    }
146
147    #endregion
148
149    #region Public Methods [System.Random functionally equivalent methods]
150
151    /// <summary>
152    /// Generates a random int over the range 0 to int.MaxValue-1.
153    /// MaxValue is not generated in order to remain functionally equivalent to System.Random.Next().
154    /// This does slightly eat into some of the performance gain over System.Random, but not much.
155    /// For better performance see:
156    ///
157    /// Call NextInt() for an int over the range 0 to int.MaxValue.
158    ///
159    /// Call NextUInt() and cast the result to an int to generate an int over the full Int32 value range
160    /// including negative values.
161    /// </summary>
162    public int Next() {
163      uint t = _x ^ (_x << 11);
164      _x = _y; _y = _z; _z = _w;
165      _w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8));
166
167      // Handle the special case where the value int.MaxValue is generated. This is outside of
168      // the range of permitted values, so we therefore call Next() to try again.
169      uint rtn = _w & 0x7FFFFFFF;
170      if (rtn == 0x7FFFFFFF) {
171        return Next();
172      }
173      return (int)rtn;
174    }
175
176    /// <summary>
177    /// Generates a random int over the range 0 to upperBound-1, and not including upperBound.
178    /// </summary>
179    public int Next(int upperBound) {
180      if (upperBound < 0) {
181        throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=0");
182      }
183
184      uint t = _x ^ (_x << 11);
185      _x = _y; _y = _z; _z = _w;
186
187      // ENHANCEMENT: Can we do this without converting to a double and back again?
188      // The explicit int cast before the first multiplication gives better performance.
189      // See comments in NextDouble.
190      return (int)((REAL_UNIT_INT * (int)(0x7FFFFFFF & (_w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8))))) * upperBound);
191    }
192
193    /// <summary>
194    /// Generates a random int over the range lowerBound to upperBound-1, and not including upperBound.
195    /// upperBound must be >= lowerBound. lowerBound may be negative.
196    /// </summary>
197    public int Next(int lowerBound, int upperBound) {
198      if (lowerBound > upperBound) {
199        throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=lowerBound");
200      }
201
202      uint t = _x ^ (_x << 11);
203      _x = _y; _y = _z; _z = _w;
204
205      // The explicit int cast before the first multiplication gives better performance.
206      // See comments in NextDouble.
207      int range = upperBound - lowerBound;
208      if (range < 0) {   // If range is <0 then an overflow has occured and must resort to using long integer arithmetic instead (slower).
209        // We also must use all 32 bits of precision, instead of the normal 31, which again is slower. 
210        return lowerBound + (int)((REAL_UNIT_UINT * (double)(_w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8)))) * (double)((long)upperBound - (long)lowerBound));
211      }
212
213      // 31 bits of precision will suffice if range<=int.MaxValue. This allows us to cast to an int and gain
214      // a little more performance.
215      return lowerBound + (int)((REAL_UNIT_INT * (double)(int)(0x7FFFFFFF & (_w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8))))) * (double)range);
216    }
217
218    /// <summary>
219    /// Generates a random double. Values returned are over the range [0, 1). That is, inclusive of 0.0 and exclusive of 1.0.
220    /// </summary>
221    public double NextDouble() {
222      uint t = _x ^ (_x << 11);
223      _x = _y; _y = _z; _z = _w;
224
225      // Here we can gain a 2x speed improvement by generating a value that can be cast to
226      // an int instead of the more easily available uint. If we then explicitly cast to an
227      // int the compiler will then cast the int to a double to perform the multiplication,
228      // this final cast is a lot faster than casting from a uint to a double. The extra cast
229      // to an int is very fast (the allocated bits remain the same) and so the overall effect
230      // of the extra cast is a significant performance improvement.
231      //
232      // Also note that the loss of one bit of precision is equivalent to what occurs within
233      // System.Random.
234      return REAL_UNIT_INT * (int)(0x7FFFFFFF & (_w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8))));
235    }
236
237    /// <summary>
238    /// Fills the provided byte array with random bytes.
239    /// This method is functionally equivalent to System.Random.NextBytes().
240    /// </summary>
241    public void NextBytes(byte[] buffer) {
242      // Fill up the bulk of the buffer in chunks of 4 bytes at a time.
243      uint x = this._x, y = this._y, z = this._z, w = this._w;
244      int i = 0;
245      uint t;
246      for (int bound = buffer.Length - 3; i < bound; ) {
247        // Generate 4 bytes.
248        // Increased performance is achieved by generating 4 random bytes per loop.
249        // Also note that no mask needs to be applied to zero out the higher order bytes before
250        // casting because the cast ignores thos bytes. Thanks to Stefan Trosch�tz for pointing this out.
251        t = x ^ (x << 11);
252        x = y; y = z; z = w;
253        w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
254
255        buffer[i++] = (byte)w;
256        buffer[i++] = (byte)(w >> 8);
257        buffer[i++] = (byte)(w >> 16);
258        buffer[i++] = (byte)(w >> 24);
259      }
260
261      // Fill up any remaining bytes in the buffer.
262      if (i < buffer.Length) {
263        // Generate 4 bytes.
264        t = x ^ (x << 11);
265        x = y; y = z; z = w;
266        w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
267
268        buffer[i++] = (byte)w;
269        if (i < buffer.Length) {
270          buffer[i++] = (byte)(w >> 8);
271          if (i < buffer.Length) {
272            buffer[i++] = (byte)(w >> 16);
273            if (i < buffer.Length) {
274              buffer[i] = (byte)(w >> 24);
275            }
276          }
277        }
278      }
279      this._x = x; this._y = y; this._z = z; this._w = w;
280    }
281
282    ///// <summary>
283    ///// A version of NextBytes that uses a pointer to set 4 bytes of the byte buffer in one operation
284    ///// thus providing a nice speedup. The loop is also partially unrolled to allow out-of-order-execution,
285    ///// this results in about a x2 speedup on an AMD Athlon. Thus performance may vary wildly on different CPUs
286    ///// depending on the number of execution units available.
287    /////
288    ///// Another significant speedup is obtained by setting the 4 bytes by indexing pDWord (e.g. pDWord[i++]=_w)
289    ///// instead of dereferencing it (e.g. *pDWord++=_w).
290    /////
291    ///// Note that this routine requires the unsafe compilation flag to be specified and so is commented out by default.
292    ///// </summary>
293    ///// <param name="buffer"></param>
294    //      public unsafe void NextBytesUnsafe(byte[] buffer)
295    //      {
296    //          if(buffer.Length % 8 != 0)
297    //              throw new ArgumentException("Buffer length must be divisible by 8", "buffer");
298    //
299    //          uint _x=this._x, _y=this._y, _z=this._z, _w=this._w;
300    //         
301    //          fixed(byte* pByte0 = buffer)
302    //          {
303    //              uint* pDWord = (uint*)pByte0;
304    //              for(int i=0, len=buffer.Length>>2; i < len; i+=2)
305    //              {
306    //                  uint t=(_x^(_x<<11));
307    //                  _x=_y; _y=_z; _z=_w;
308    //                  pDWord[i] = _w = (_w^(_w>>19))^(t^(t>>8));
309    //
310    //                  t=(_x^(_x<<11));
311    //                  _x=_y; _y=_z; _z=_w;
312    //                  pDWord[i+1] = _w = (_w^(_w>>19))^(t^(t>>8));
313    //              }
314    //          }
315    //
316    //          this._x=_x; this._y=_y; this._z=_z; this._w=_w;
317    //      }
318    #endregion
319
320    #region Public Methods [Methods not present on System.Random]
321
322    /// <summary>
323    /// Generates a uint. Values returned are over the full range of a uint,
324    /// uint.MinValue to uint.MaxValue, inclusive.
325    ///
326    /// This is the fastest method for generating a single random number because the underlying
327    /// random number generator algorithm generates 32 random bits that can be cast directly to
328    /// a uint.
329    /// </summary>
330    public uint NextUInt() {
331      uint t = _x ^ (_x << 11);
332      _x = _y; _y = _z; _z = _w;
333      return _w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8));
334    }
335
336    /// <summary>
337    /// Generates a random int over the range 0 to int.MaxValue, inclusive.
338    /// This method differs from Next() only in that the range is 0 to int.MaxValue
339    /// and not 0 to int.MaxValue-1.
340    ///
341    /// The slight difference in range means this method is slightly faster than Next()
342    /// but is not functionally equivalent to System.Random.Next().
343    /// </summary>
344    public int NextInt() {
345      uint t = _x ^ (_x << 11);
346      _x = _y; _y = _z; _z = _w;
347      return (int)(0x7FFFFFFF & (_w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8))));
348    }
349
350    /// <summary>
351    /// Generates a random double. Values returned are over the range (0, 1). That is, exclusive of both 0.0 and 1.0.
352    /// </summary>
353    public double NextDoubleNonZero() {
354      uint t = _x ^ (_x << 11);
355      _x = _y; _y = _z; _z = _w;
356
357      // See notes on NextDouble(). Here we generate a random value from 0 to 0x7f ff ff fe, and add one
358      // to generate a random value from 1 to 0x7f ff ff ff.
359      return REAL_UNIT_INT * (int)((0x7FFFFFFE & (_w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8)))) + 1U);
360    }
361
362    // Buffer 32 bits in bitBuffer, return 1 at a time, keep track of how many have been returned
363    // with bitMask.
364    uint _bitBuffer;
365    uint _bitMask;
366
367    /// <summary>
368    /// Generates a single random bit.
369    /// This method's performance is improved by generating 32 bits in one operation and storing them
370    /// ready for future calls.
371    /// </summary>
372    public bool NextBool() {
373      if (0 == _bitMask) {
374        // Generate 32 more bits.
375        uint t = _x ^ (_x << 11);
376        _x = _y; _y = _z; _z = _w;
377        _bitBuffer = _w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8));
378
379        // Reset the bitMask that tells us which bit to read next.
380        _bitMask = 0x80000000;
381        return (_bitBuffer & _bitMask) == 0;
382      }
383
384      return (_bitBuffer & (_bitMask >>= 1)) == 0;
385    }
386
387    // Buffer of random bytes. A single UInt32 is used to buffer 4 bytes.
388    // _byteBufferState tracks how bytes remain in the buffer, a value of
389    // zero  indicates that the buffer is empty.
390    uint _byteBuffer;
391    byte _byteBufferState;
392
393    /// <summary>
394    /// Generates a signle random byte with range [0,255].
395    /// This method's performance is improved by generating 4 bytes in one operation and storing them
396    /// ready for future calls.
397    /// </summary>
398    public byte NextByte() {
399      if (0 == _byteBufferState) {
400        // Generate 4 more bytes.
401        uint t = _x ^ (_x << 11);
402        _x = _y; _y = _z; _z = _w;
403        _byteBuffer = _w = (_w ^ (_w >> 19)) ^ (t ^ (t >> 8));
404        _byteBufferState = 0x4;
405        return (byte)_byteBuffer;  // Note. Masking with 0xFF is unnecessary.
406      }
407      _byteBufferState >>= 1;
408      return (byte)(_byteBuffer >>= 1);
409    }
410
411    #endregion
412  }
413}
Note: See TracBrowser for help on using the repository browser.