Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Random/3.3/FastRandom.cs @ 7108

Last change on this file since 7108 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 14.6 KB
Line 
1using System;
2using HeuristicLab.Common;
3using HeuristicLab.Core;
4using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
5
6namespace HeuristicLab.Random {
7  /// <summary>
8  /// A fast random number generator for .NET
9  /// Colin Green, January 2005
10  ///
11  /// September 4th 2005
12  ///  Added NextBytesUnsafe() - commented out by default.
13  ///  Fixed bug in Reinitialise() - y,z and w variables were not being reset.
14  ///
15  /// Key points:
16  ///  1) Based on a simple and fast xor-shift pseudo random number generator (RNG) specified in:
17  ///  Marsaglia, George. (2003). Xorshift RNGs.
18  ///  http://www.jstatsoft.org/v08/i14/xorshift.pdf
19  /// 
20  ///  This particular implementation of xorshift has a period of 2^128-1. See the above paper to see
21  ///  how this can be easily extened if you need a longer period. At the time of writing I could find no
22  ///  information on the period of System.Random for comparison.
23  ///
24  ///  2) Faster than System.Random. Up to 8x faster, depending on which methods are called.
25  ///
26  ///  3) Direct replacement for System.Random. This class implements all of the methods that System.Random
27  ///  does plus some additional methods. The like named methods are functionally equivalent.
28  /// 
29  ///  4) Allows fast re-initialisation with a seed, unlike System.Random which accepts a seed at construction
30  ///  time which then executes a relatively expensive initialisation routine. This provides a vast speed improvement
31  ///  if you need to reset the pseudo-random number sequence many times, e.g. if you want to re-generate the same
32  ///  sequence many times. An alternative might be to cache random numbers in an array, but that approach is limited
33  ///  by memory capacity and the fact that you may also want a large number of different sequences cached. Each sequence
34  ///  can each be represented by a single seed value (int) when using FastRandom.
35  /// 
36  ///  Notes.
37  ///  A further performance improvement can be obtained by declaring local variables as static, thus avoiding
38  ///  re-allocation of variables on each call. However care should be taken if multiple instances of
39  ///  FastRandom are in use or if being used in a multi-threaded environment.
40  ///
41  /// August 2010:
42  ///   adapted for HeuristicLab by gkronber (cloning, persistence, IRandom interface)
43  ///   
44  /// </summary>
45  [StorableClass]
46  public sealed class FastRandom : Item, IRandom {
47    // The +1 ensures NextDouble doesn't generate 1.0
48    private const double REAL_UNIT_INT = 1.0 / ((double)int.MaxValue + 1.0);
49    private const double REAL_UNIT_UINT = 1.0 / ((double)uint.MaxValue + 1.0);
50    private const uint Y = 842502087, Z = 3579807591, W = 273326509;
51
52    [Storable]
53    private uint x, y, z, w;
54
55    #region Constructors
56    /// <summary>
57    /// Used by HeuristicLab.Persistence to initialize new instances during deserialization.
58    /// </summary>
59    /// <param name="deserializing">true, if the constructor is called during deserialization.</param>
60    [StorableConstructor]
61    private FastRandom(bool deserializing) : base(deserializing) { }
62
63    /// <summary>
64    /// Initializes a new instance from an existing one (copy constructor).
65    /// </summary>
66    /// <param name="original">The original <see cref="FastRandom"/> instance which is used to initialize the new instance.</param>
67    /// <param name="cloner">A <see cref="Cloner"/> which is used to track all already cloned objects in order to avoid cycles.</param>
68    private FastRandom(FastRandom original, Cloner cloner)
69      : base(original, cloner) {
70      x = original.x;
71      y = original.y;
72      z = original.z;
73      w = original.w;
74      bitBuffer = original.bitBuffer;
75      bitMask = original.bitMask;
76    }
77
78    /// <summary>
79    /// Initialises a new instance using time dependent seed.
80    /// </summary>
81    public FastRandom() {
82      // Initialise using the system tick count.
83      Reinitialise((int)Environment.TickCount);
84    }
85
86    /// <summary>
87    /// Initialises a new instance using an int value as seed.
88    /// This constructor signature is provided to maintain compatibility with
89    /// System.Random
90    /// </summary>
91    public FastRandom(int seed) {
92      Reinitialise(seed);
93    }
94    #endregion
95
96    #region Public Methods [Reinitialisation]
97
98    /// <summary>
99    /// Reinitialises using an int value as a seed.
100    /// </summary>
101    /// <param name="seed"></param>
102    public void Reinitialise(int seed) {
103      // The only stipulation stated for the xorshift RNG is that at least one of
104      // the seeds x,y,z,w is non-zero. We fulfill that requirement by only allowing
105      // resetting of the x seed
106      x = (uint)seed;
107      y = Y;
108      z = Z;
109      w = W;
110    }
111
112    #endregion
113
114    #region Public Methods [System.Random functionally equivalent methods]
115
116    /// <summary>
117    /// Generates a random int over the range 0 to int.MaxValue-1.
118    /// MaxValue is not generated in order to remain functionally equivalent to System.Random.Next().
119    /// This does slightly eat into some of the performance gain over System.Random, but not much.
120    /// For better performance see:
121    ///
122    /// Call NextInt() for an int over the range 0 to int.MaxValue.
123    ///
124    /// Call NextUInt() and cast the result to an int to generate an int over the full Int32 value range
125    /// including negative values.
126    /// </summary>
127    /// <returns></returns>
128    public int Next() {
129      uint t = (x ^ (x << 11));
130      x = y; y = z; z = w;
131      w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
132
133      // Handle the special case where the value int.MaxValue is generated. This is outside of
134      // the range of permitted values, so we therefore call Next() to try again.
135      uint rtn = w & 0x7FFFFFFF;
136      if (rtn == 0x7FFFFFFF)
137        return Next();
138      return (int)rtn;
139    }
140
141    /// <summary>
142    /// Generates a random int over the range 0 to upperBound-1, and not including upperBound.
143    /// </summary>
144    /// <param name="upperBound"></param>
145    /// <returns></returns>
146    public int Next(int upperBound) {
147      if (upperBound < 0)
148        throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=0");
149
150      uint t = (x ^ (x << 11));
151      x = y; y = z; z = w;
152
153      // The explicit int cast before the first multiplication gives better performance.
154      // See comments in NextDouble.
155      return (int)((REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * upperBound);
156    }
157
158    /// <summary>
159    /// Generates a random int over the range lowerBound to upperBound-1, and not including upperBound.
160    /// upperBound must be >= lowerBound. lowerBound may be negative.
161    /// </summary>
162    /// <param name="lowerBound"></param>
163    /// <param name="upperBound"></param>
164    /// <returns></returns>
165    public int Next(int lowerBound, int upperBound) {
166      if (lowerBound > upperBound)
167        throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=lowerBound");
168
169      uint t = (x ^ (x << 11));
170      x = y; y = z; z = w;
171
172      // The explicit int cast before the first multiplication gives better performance.
173      // See comments in NextDouble.
174      int range = upperBound - lowerBound;
175      if (range < 0) {  // If range is <0 then an overflow has occured and must resort to using long integer arithmetic instead (slower).
176        // We also must use all 32 bits of precision, instead of the normal 31, which again is slower. 
177        return lowerBound + (int)((REAL_UNIT_UINT * (double)(w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))) * (double)((long)upperBound - (long)lowerBound));
178      }
179
180      // 31 bits of precision will suffice if range<=int.MaxValue. This allows us to cast to an int and gain
181      // a little more performance.
182      return lowerBound + (int)((REAL_UNIT_INT * (double)(int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * (double)range);
183    }
184
185    /// <summary>
186    /// Generates a random double. Values returned are from 0.0 up to but not including 1.0.
187    /// </summary>
188    /// <returns></returns>
189    public double NextDouble() {
190      uint t = (x ^ (x << 11));
191      x = y; y = z; z = w;
192
193      // Here we can gain a 2x speed improvement by generating a value that can be cast to
194      // an int instead of the more easily available uint. If we then explicitly cast to an
195      // int the compiler will then cast the int to a double to perform the multiplication,
196      // this final cast is a lot faster than casting from a uint to a double. The extra cast
197      // to an int is very fast (the allocated bits remain the same) and so the overall effect
198      // of the extra cast is a significant performance improvement.
199      //
200      // Also note that the loss of one bit of precision is equivalent to what occurs within
201      // System.Random.
202      return (REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))));
203    }
204
205
206    /// <summary>
207    /// Fills the provided byte array with random bytes.
208    /// This method is functionally equivalent to System.Random.NextBytes().
209    /// </summary>
210    /// <param name="buffer"></param>
211    public void NextBytes(byte[] buffer) {
212      // Fill up the bulk of the buffer in chunks of 4 bytes at a time.
213      uint x = this.x, y = this.y, z = this.z, w = this.w;
214      int i = 0;
215      uint t;
216      for (int bound = buffer.Length - 3; i < bound; ) {
217        // Generate 4 bytes.
218        // Increased performance is achieved by generating 4 random bytes per loop.
219        // Also note that no mask needs to be applied to zero out the higher order bytes before
220        // casting because the cast ignores thos bytes. Thanks to Stefan Trosch�tz for pointing this out.
221        t = (x ^ (x << 11));
222        x = y; y = z; z = w;
223        w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
224
225        buffer[i++] = (byte)w;
226        buffer[i++] = (byte)(w >> 8);
227        buffer[i++] = (byte)(w >> 16);
228        buffer[i++] = (byte)(w >> 24);
229      }
230
231      // Fill up any remaining bytes in the buffer.
232      if (i < buffer.Length) {
233        // Generate 4 bytes.
234        t = (x ^ (x << 11));
235        x = y; y = z; z = w;
236        w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
237
238        buffer[i++] = (byte)w;
239        if (i < buffer.Length) {
240          buffer[i++] = (byte)(w >> 8);
241          if (i < buffer.Length) {
242            buffer[i++] = (byte)(w >> 16);
243            if (i < buffer.Length) {
244              buffer[i] = (byte)(w >> 24);
245            }
246          }
247        }
248      }
249      this.x = x; this.y = y; this.z = z; this.w = w;
250    }
251
252
253    //    /// <summary>
254    //    /// A version of NextBytes that uses a pointer to set 4 bytes of the byte buffer in one operation
255    //    /// thus providing a nice speedup. The loop is also partially unrolled to allow out-of-order-execution,
256    //    /// this results in about a x2 speedup on an AMD Athlon. Thus performance may vary wildly on different CPUs
257    //    /// depending on the number of execution units available.
258    //    ///
259    //    /// Another significant speedup is obtained by setting the 4 bytes by indexing pDWord (e.g. pDWord[i++]=w)
260    //    /// instead of adjusting it dereferencing it (e.g. *pDWord++=w).
261    //    ///
262    //    /// Note that this routine requires the unsafe compilation flag to be specified and so is commented out by default.
263    //    /// </summary>
264    //    /// <param name="buffer"></param>
265    //    public unsafe void NextBytesUnsafe(byte[] buffer)
266    //    {
267    //      if(buffer.Length % 8 != 0)
268    //        throw new ArgumentException("Buffer length must be divisible by 8", "buffer");
269    //
270    //      uint x=this.x, y=this.y, z=this.z, w=this.w;
271    //     
272    //      fixed(byte* pByte0 = buffer)
273    //      {
274    //        uint* pDWord = (uint*)pByte0;
275    //        for(int i=0, len=buffer.Length>>2; i < len; i+=2)
276    //        {
277    //          uint t=(x^(x<<11));
278    //          x=y; y=z; z=w;
279    //          pDWord[i] = w = (w^(w>>19))^(t^(t>>8));
280    //
281    //          t=(x^(x<<11));
282    //          x=y; y=z; z=w;
283    //          pDWord[i+1] = w = (w^(w>>19))^(t^(t>>8));
284    //        }
285    //      }
286    //
287    //      this.x=x; this.y=y; this.z=z; this.w=w;
288    //    }
289
290    #endregion
291
292    #region Public Methods [Methods not present on System.Random]
293
294    /// <summary>
295    /// Generates a uint. Values returned are over the full range of a uint,
296    /// uint.MinValue to uint.MaxValue, inclusive.
297    ///
298    /// This is the fastest method for generating a single random number because the underlying
299    /// random number generator algorithm generates 32 random bits that can be cast directly to
300    /// a uint.
301    /// </summary>
302    /// <returns></returns>
303    public uint NextUInt() {
304      uint t = (x ^ (x << 11));
305      x = y; y = z; z = w;
306      return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)));
307    }
308
309    /// <summary>
310    /// Generates a random int over the range 0 to int.MaxValue, inclusive.
311    /// This method differs from Next() only in that the range is 0 to int.MaxValue
312    /// and not 0 to int.MaxValue-1.
313    ///
314    /// The slight difference in range means this method is slightly faster than Next()
315    /// but is not functionally equivalent to System.Random.Next().
316    /// </summary>
317    /// <returns></returns>
318    public int NextInt() {
319      uint t = (x ^ (x << 11));
320      x = y; y = z; z = w;
321      return (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))));
322    }
323
324    /// <summary>
325    /// Generates a single random bit.
326    /// This method's performance is improved by generating 32 bits in one operation and storing them
327    /// ready for future calls.
328    /// </summary>
329    /// <returns></returns>
330    public bool NextBool() {
331      if (bitMask == 1) {
332        // Generate 32 more bits.
333        uint t = (x ^ (x << 11));
334        x = y; y = z; z = w;
335        bitBuffer = w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
336
337        // Reset the bitMask that tells us which bit to read next.
338        bitMask = 0x80000000;
339        return (bitBuffer & bitMask) == 0;
340      }
341      return (bitBuffer & (bitMask >>= 1)) == 0;
342    }
343    // Buffer 32 bits in bitBuffer, return 1 at a time, keep track of how many have been returned
344    // with bitBufferIdx.
345    [Storable]
346    private uint bitBuffer;
347    [Storable]
348    private uint bitMask = 1;
349
350
351    #endregion
352
353    #region IRandom Members
354
355    public void Reset() {
356      Reinitialise((int)Environment.TickCount);
357    }
358
359    public void Reset(int seed) {
360      Reinitialise(seed);
361    }
362
363    #endregion
364
365    public override IDeepCloneable Clone(Cloner cloner) {
366      return new FastRandom(this, cloner);
367    }
368  }
369}
Note: See TracBrowser for help on using the repository browser.