[4243] | 1 | using System;
|
---|
[4258] | 2 | using HeuristicLab.Common;
|
---|
[4243] | 3 | using HeuristicLab.Core;
|
---|
| 4 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
| 5 |
|
---|
| 6 | namespace 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]
|
---|
[4258] | 46 | public sealed class FastRandom : Item, IRandom {
|
---|
[4243] | 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 |
|
---|
| 57 | /// <summary>
|
---|
| 58 | /// Initialises a new instance using time dependent seed.
|
---|
| 59 | /// </summary>
|
---|
| 60 | public FastRandom() {
|
---|
| 61 | // Initialise using the system tick count.
|
---|
| 62 | Reinitialise((int)Environment.TickCount);
|
---|
| 63 | }
|
---|
| 64 |
|
---|
| 65 | /// <summary>
|
---|
| 66 | /// Initialises a new instance using an int value as seed.
|
---|
| 67 | /// This constructor signature is provided to maintain compatibility with
|
---|
| 68 | /// System.Random
|
---|
| 69 | /// </summary>
|
---|
| 70 | public FastRandom(int seed) {
|
---|
| 71 | Reinitialise(seed);
|
---|
| 72 | }
|
---|
| 73 |
|
---|
[4258] | 74 | /// <summary>
|
---|
| 75 | /// Used by HeuristicLab.Persistence to initialize new instances during deserialization.
|
---|
| 76 | /// </summary>
|
---|
| 77 | /// <param name="deserializing">true, if the constructor is called during deserialization.</param>
|
---|
| 78 | [StorableConstructor]
|
---|
| 79 | private FastRandom(bool deserializing) : base(deserializing) { }
|
---|
| 80 |
|
---|
[4243] | 81 | #endregion
|
---|
| 82 |
|
---|
| 83 | #region Public Methods [Reinitialisation]
|
---|
| 84 |
|
---|
| 85 | /// <summary>
|
---|
| 86 | /// Reinitialises using an int value as a seed.
|
---|
| 87 | /// </summary>
|
---|
| 88 | /// <param name="seed"></param>
|
---|
| 89 | public void Reinitialise(int seed) {
|
---|
| 90 | // The only stipulation stated for the xorshift RNG is that at least one of
|
---|
| 91 | // the seeds x,y,z,w is non-zero. We fulfill that requirement by only allowing
|
---|
| 92 | // resetting of the x seed
|
---|
| 93 | x = (uint)seed;
|
---|
| 94 | y = Y;
|
---|
| 95 | z = Z;
|
---|
| 96 | w = W;
|
---|
| 97 | }
|
---|
| 98 |
|
---|
| 99 | #endregion
|
---|
| 100 |
|
---|
| 101 | #region Public Methods [System.Random functionally equivalent methods]
|
---|
| 102 |
|
---|
| 103 | /// <summary>
|
---|
| 104 | /// Generates a random int over the range 0 to int.MaxValue-1.
|
---|
| 105 | /// MaxValue is not generated in order to remain functionally equivalent to System.Random.Next().
|
---|
| 106 | /// This does slightly eat into some of the performance gain over System.Random, but not much.
|
---|
| 107 | /// For better performance see:
|
---|
| 108 | ///
|
---|
| 109 | /// Call NextInt() for an int over the range 0 to int.MaxValue.
|
---|
| 110 | ///
|
---|
| 111 | /// Call NextUInt() and cast the result to an int to generate an int over the full Int32 value range
|
---|
| 112 | /// including negative values.
|
---|
| 113 | /// </summary>
|
---|
| 114 | /// <returns></returns>
|
---|
| 115 | public int Next() {
|
---|
| 116 | uint t = (x ^ (x << 11));
|
---|
| 117 | x = y; y = z; z = w;
|
---|
| 118 | w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
|
---|
| 119 |
|
---|
| 120 | // Handle the special case where the value int.MaxValue is generated. This is outside of
|
---|
| 121 | // the range of permitted values, so we therefore call Next() to try again.
|
---|
| 122 | uint rtn = w & 0x7FFFFFFF;
|
---|
| 123 | if (rtn == 0x7FFFFFFF)
|
---|
| 124 | return Next();
|
---|
| 125 | return (int)rtn;
|
---|
| 126 | }
|
---|
| 127 |
|
---|
| 128 | /// <summary>
|
---|
| 129 | /// Generates a random int over the range 0 to upperBound-1, and not including upperBound.
|
---|
| 130 | /// </summary>
|
---|
| 131 | /// <param name="upperBound"></param>
|
---|
| 132 | /// <returns></returns>
|
---|
| 133 | public int Next(int upperBound) {
|
---|
| 134 | if (upperBound < 0)
|
---|
| 135 | throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=0");
|
---|
| 136 |
|
---|
| 137 | uint t = (x ^ (x << 11));
|
---|
| 138 | x = y; y = z; z = w;
|
---|
| 139 |
|
---|
| 140 | // The explicit int cast before the first multiplication gives better performance.
|
---|
| 141 | // See comments in NextDouble.
|
---|
| 142 | return (int)((REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * upperBound);
|
---|
| 143 | }
|
---|
| 144 |
|
---|
| 145 | /// <summary>
|
---|
| 146 | /// Generates a random int over the range lowerBound to upperBound-1, and not including upperBound.
|
---|
| 147 | /// upperBound must be >= lowerBound. lowerBound may be negative.
|
---|
| 148 | /// </summary>
|
---|
| 149 | /// <param name="lowerBound"></param>
|
---|
| 150 | /// <param name="upperBound"></param>
|
---|
| 151 | /// <returns></returns>
|
---|
| 152 | public int Next(int lowerBound, int upperBound) {
|
---|
| 153 | if (lowerBound > upperBound)
|
---|
| 154 | throw new ArgumentOutOfRangeException("upperBound", upperBound, "upperBound must be >=lowerBound");
|
---|
| 155 |
|
---|
| 156 | uint t = (x ^ (x << 11));
|
---|
| 157 | x = y; y = z; z = w;
|
---|
| 158 |
|
---|
| 159 | // The explicit int cast before the first multiplication gives better performance.
|
---|
| 160 | // See comments in NextDouble.
|
---|
| 161 | int range = upperBound - lowerBound;
|
---|
| 162 | if (range < 0) { // If range is <0 then an overflow has occured and must resort to using long integer arithmetic instead (slower).
|
---|
| 163 | // We also must use all 32 bits of precision, instead of the normal 31, which again is slower.
|
---|
| 164 | return lowerBound + (int)((REAL_UNIT_UINT * (double)(w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))) * (double)((long)upperBound - (long)lowerBound));
|
---|
| 165 | }
|
---|
| 166 |
|
---|
| 167 | // 31 bits of precision will suffice if range<=int.MaxValue. This allows us to cast to an int and gain
|
---|
| 168 | // a little more performance.
|
---|
| 169 | return lowerBound + (int)((REAL_UNIT_INT * (double)(int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))))) * (double)range);
|
---|
| 170 | }
|
---|
| 171 |
|
---|
| 172 | /// <summary>
|
---|
| 173 | /// Generates a random double. Values returned are from 0.0 up to but not including 1.0.
|
---|
| 174 | /// </summary>
|
---|
| 175 | /// <returns></returns>
|
---|
| 176 | public double NextDouble() {
|
---|
| 177 | uint t = (x ^ (x << 11));
|
---|
| 178 | x = y; y = z; z = w;
|
---|
| 179 |
|
---|
| 180 | // Here we can gain a 2x speed improvement by generating a value that can be cast to
|
---|
| 181 | // an int instead of the more easily available uint. If we then explicitly cast to an
|
---|
| 182 | // int the compiler will then cast the int to a double to perform the multiplication,
|
---|
| 183 | // this final cast is a lot faster than casting from a uint to a double. The extra cast
|
---|
| 184 | // to an int is very fast (the allocated bits remain the same) and so the overall effect
|
---|
| 185 | // of the extra cast is a significant performance improvement.
|
---|
| 186 | //
|
---|
| 187 | // Also note that the loss of one bit of precision is equivalent to what occurs within
|
---|
| 188 | // System.Random.
|
---|
| 189 | return (REAL_UNIT_INT * (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)))));
|
---|
| 190 | }
|
---|
| 191 |
|
---|
| 192 |
|
---|
| 193 | /// <summary>
|
---|
| 194 | /// Fills the provided byte array with random bytes.
|
---|
| 195 | /// This method is functionally equivalent to System.Random.NextBytes().
|
---|
| 196 | /// </summary>
|
---|
| 197 | /// <param name="buffer"></param>
|
---|
| 198 | public void NextBytes(byte[] buffer) {
|
---|
| 199 | // Fill up the bulk of the buffer in chunks of 4 bytes at a time.
|
---|
| 200 | uint x = this.x, y = this.y, z = this.z, w = this.w;
|
---|
| 201 | int i = 0;
|
---|
| 202 | uint t;
|
---|
| 203 | for (int bound = buffer.Length - 3; i < bound; ) {
|
---|
| 204 | // Generate 4 bytes.
|
---|
| 205 | // Increased performance is achieved by generating 4 random bytes per loop.
|
---|
| 206 | // Also note that no mask needs to be applied to zero out the higher order bytes before
|
---|
| 207 | // casting because the cast ignores thos bytes. Thanks to Stefan Trosch�tz for pointing this out.
|
---|
| 208 | t = (x ^ (x << 11));
|
---|
| 209 | x = y; y = z; z = w;
|
---|
| 210 | w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
|
---|
| 211 |
|
---|
| 212 | buffer[i++] = (byte)w;
|
---|
| 213 | buffer[i++] = (byte)(w >> 8);
|
---|
| 214 | buffer[i++] = (byte)(w >> 16);
|
---|
| 215 | buffer[i++] = (byte)(w >> 24);
|
---|
| 216 | }
|
---|
| 217 |
|
---|
| 218 | // Fill up any remaining bytes in the buffer.
|
---|
| 219 | if (i < buffer.Length) {
|
---|
| 220 | // Generate 4 bytes.
|
---|
| 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 | if (i < buffer.Length) {
|
---|
| 227 | buffer[i++] = (byte)(w >> 8);
|
---|
| 228 | if (i < buffer.Length) {
|
---|
| 229 | buffer[i++] = (byte)(w >> 16);
|
---|
| 230 | if (i < buffer.Length) {
|
---|
| 231 | buffer[i] = (byte)(w >> 24);
|
---|
| 232 | }
|
---|
| 233 | }
|
---|
| 234 | }
|
---|
| 235 | }
|
---|
| 236 | this.x = x; this.y = y; this.z = z; this.w = w;
|
---|
| 237 | }
|
---|
| 238 |
|
---|
| 239 |
|
---|
| 240 | // /// <summary>
|
---|
| 241 | // /// A version of NextBytes that uses a pointer to set 4 bytes of the byte buffer in one operation
|
---|
| 242 | // /// thus providing a nice speedup. The loop is also partially unrolled to allow out-of-order-execution,
|
---|
| 243 | // /// this results in about a x2 speedup on an AMD Athlon. Thus performance may vary wildly on different CPUs
|
---|
| 244 | // /// depending on the number of execution units available.
|
---|
| 245 | // ///
|
---|
| 246 | // /// Another significant speedup is obtained by setting the 4 bytes by indexing pDWord (e.g. pDWord[i++]=w)
|
---|
| 247 | // /// instead of adjusting it dereferencing it (e.g. *pDWord++=w).
|
---|
| 248 | // ///
|
---|
| 249 | // /// Note that this routine requires the unsafe compilation flag to be specified and so is commented out by default.
|
---|
| 250 | // /// </summary>
|
---|
| 251 | // /// <param name="buffer"></param>
|
---|
| 252 | // public unsafe void NextBytesUnsafe(byte[] buffer)
|
---|
| 253 | // {
|
---|
| 254 | // if(buffer.Length % 8 != 0)
|
---|
| 255 | // throw new ArgumentException("Buffer length must be divisible by 8", "buffer");
|
---|
| 256 | //
|
---|
| 257 | // uint x=this.x, y=this.y, z=this.z, w=this.w;
|
---|
| 258 | //
|
---|
| 259 | // fixed(byte* pByte0 = buffer)
|
---|
| 260 | // {
|
---|
| 261 | // uint* pDWord = (uint*)pByte0;
|
---|
| 262 | // for(int i=0, len=buffer.Length>>2; i < len; i+=2)
|
---|
| 263 | // {
|
---|
| 264 | // uint t=(x^(x<<11));
|
---|
| 265 | // x=y; y=z; z=w;
|
---|
| 266 | // pDWord[i] = w = (w^(w>>19))^(t^(t>>8));
|
---|
| 267 | //
|
---|
| 268 | // t=(x^(x<<11));
|
---|
| 269 | // x=y; y=z; z=w;
|
---|
| 270 | // pDWord[i+1] = w = (w^(w>>19))^(t^(t>>8));
|
---|
| 271 | // }
|
---|
| 272 | // }
|
---|
| 273 | //
|
---|
| 274 | // this.x=x; this.y=y; this.z=z; this.w=w;
|
---|
| 275 | // }
|
---|
| 276 |
|
---|
| 277 | #endregion
|
---|
| 278 |
|
---|
| 279 | #region Public Methods [Methods not present on System.Random]
|
---|
| 280 |
|
---|
| 281 | /// <summary>
|
---|
| 282 | /// Generates a uint. Values returned are over the full range of a uint,
|
---|
| 283 | /// uint.MinValue to uint.MaxValue, inclusive.
|
---|
| 284 | ///
|
---|
| 285 | /// This is the fastest method for generating a single random number because the underlying
|
---|
| 286 | /// random number generator algorithm generates 32 random bits that can be cast directly to
|
---|
| 287 | /// a uint.
|
---|
| 288 | /// </summary>
|
---|
| 289 | /// <returns></returns>
|
---|
| 290 | public uint NextUInt() {
|
---|
| 291 | uint t = (x ^ (x << 11));
|
---|
| 292 | x = y; y = z; z = w;
|
---|
| 293 | return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)));
|
---|
| 294 | }
|
---|
| 295 |
|
---|
| 296 | /// <summary>
|
---|
| 297 | /// Generates a random int over the range 0 to int.MaxValue, inclusive.
|
---|
| 298 | /// This method differs from Next() only in that the range is 0 to int.MaxValue
|
---|
| 299 | /// and not 0 to int.MaxValue-1.
|
---|
| 300 | ///
|
---|
| 301 | /// The slight difference in range means this method is slightly faster than Next()
|
---|
| 302 | /// but is not functionally equivalent to System.Random.Next().
|
---|
| 303 | /// </summary>
|
---|
| 304 | /// <returns></returns>
|
---|
| 305 | public int NextInt() {
|
---|
| 306 | uint t = (x ^ (x << 11));
|
---|
| 307 | x = y; y = z; z = w;
|
---|
| 308 | return (int)(0x7FFFFFFF & (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))));
|
---|
| 309 | }
|
---|
| 310 |
|
---|
| 311 | /// <summary>
|
---|
| 312 | /// Generates a single random bit.
|
---|
| 313 | /// This method's performance is improved by generating 32 bits in one operation and storing them
|
---|
| 314 | /// ready for future calls.
|
---|
| 315 | /// </summary>
|
---|
| 316 | /// <returns></returns>
|
---|
| 317 | public bool NextBool() {
|
---|
| 318 | if (bitMask == 1) {
|
---|
| 319 | // Generate 32 more bits.
|
---|
| 320 | uint t = (x ^ (x << 11));
|
---|
| 321 | x = y; y = z; z = w;
|
---|
| 322 | bitBuffer = w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
|
---|
| 323 |
|
---|
| 324 | // Reset the bitMask that tells us which bit to read next.
|
---|
| 325 | bitMask = 0x80000000;
|
---|
| 326 | return (bitBuffer & bitMask) == 0;
|
---|
| 327 | }
|
---|
| 328 | return (bitBuffer & (bitMask >>= 1)) == 0;
|
---|
[4258] | 329 | }
|
---|
[4243] | 330 | // Buffer 32 bits in bitBuffer, return 1 at a time, keep track of how many have been returned
|
---|
| 331 | // with bitBufferIdx.
|
---|
| 332 | [Storable]
|
---|
| 333 | private uint bitBuffer;
|
---|
| 334 | [Storable]
|
---|
| 335 | private uint bitMask = 1;
|
---|
| 336 |
|
---|
| 337 |
|
---|
[4258] | 338 | #endregion
|
---|
[4243] | 339 |
|
---|
| 340 | #region IRandom Members
|
---|
| 341 |
|
---|
| 342 | public void Reset() {
|
---|
| 343 | Reinitialise((int)Environment.TickCount);
|
---|
| 344 | }
|
---|
| 345 |
|
---|
| 346 | public void Reset(int seed) {
|
---|
| 347 | Reinitialise(seed);
|
---|
| 348 | }
|
---|
| 349 |
|
---|
[4258] | 350 | #endregion
|
---|
[4243] | 351 |
|
---|
[4258] | 352 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
[4243] | 353 | FastRandom clone = (FastRandom)base.Clone(cloner);
|
---|
| 354 | clone.x = x;
|
---|
| 355 | clone.y = y;
|
---|
| 356 | clone.z = z;
|
---|
| 357 | clone.w = w;
|
---|
| 358 | clone.bitBuffer = bitBuffer;
|
---|
| 359 | clone.bitMask = bitMask;
|
---|
| 360 | return clone;
|
---|
| 361 | }
|
---|
| 362 | }
|
---|
| 363 | }
|
---|