root/ext/mt-random/mt-random.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. Scm_MTInitByUI
  2. Scm_MTInitByArray
  3. Scm_MTGenrandU32
  4. Scm_MTGenrandF32
  5. Scm_MTGenrandF64
  6. xlog2
  7. genrand_int_small
  8. Scm_MTGenrandInt
  9. mt_allocate
  10. Scm_Init_mt_random

   1 /*
   2  * mt-random.c - implements MT19937 random number generation algorithm
   3  *
   4  * Mersenne Twister algorithm invented by Makoto Matsumoto & Takuji Nishimura.
   5  *   http://www.math.keio.ac.jp/~matumoto/emt.html
   6  * This code is based on mt18837ar.c (2002/1/16).   It is released under
   7  * BSD license.
   8  * I modified the code in the following parts.
   9  *   - make it modular, esp., all the state information is kept in
  10  *     the allocated memory for random number generator object.
  11  *   - changed the names of the functions
  12  *   - added stuff to make it as a Gauche extension module.
  13  * $Id: mt-random.c,v 1.16 2005/09/10 09:39:12 shirok Exp $
  14  *
  15  * The original copyright notice follows.
  16  */
  17 /*
  18    A C-program for MT19937, with initialization improved 2002/1/26.
  19    Coded by Takuji Nishimura and Makoto Matsumoto.
  20 
  21    Before using, initialize the state by using init_genrand(seed)  
  22    or init_by_array(init_key, key_length).
  23 
  24    Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  25    All rights reserved.                          
  26 
  27    Redistribution and use in source and binary forms, with or without
  28    modification, are permitted provided that the following conditions
  29    are met:
  30 
  31      1. Redistributions of source code must retain the above copyright
  32         notice, this list of conditions and the following disclaimer.
  33 
  34      2. Redistributions in binary form must reproduce the above copyright
  35         notice, this list of conditions and the following disclaimer in the
  36         documentation and/or other materials provided with the distribution.
  37 
  38      3. The names of its contributors may not be used to endorse or promote 
  39         products derived from this software without specific prior written 
  40         permission.
  41 
  42    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  43    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  44    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  45    A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  46    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  47    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  48    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  49    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  50    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  51    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  52    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  53 
  54 
  55    Any feedback is very welcome.
  56    http://www.math.keio.ac.jp/matumoto/emt.html
  57    email: matumoto@math.keio.ac.jp
  58 */
  59 
  60 #include "mt-random.h"
  61 #include <math.h>
  62 
  63 /* Period parameters */  
  64 #define M 397
  65 #define MATRIX_A 0x9908b0dfUL   /* constant vector a */
  66 #define UPPER_MASK 0x80000000UL /* most significant w-r bits */
  67 #define LOWER_MASK 0x7fffffffUL /* least significant r bits */
  68 
  69 /* initializes mt[N] with a seed */
  70 void Scm_MTInitByUI(ScmMersenneTwister *mt, unsigned long s)
  71 {
  72     int mti;
  73     mt->mt[0]= s & 0xffffffffUL;
  74     for (mti=1; mti<N; mti++) {
  75         mt->mt[mti] = 
  76             (1812433253UL * (mt->mt[mti-1] ^ (mt->mt[mti-1] >> 30)) + mti); 
  77         /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  78         /* In the previous versions, MSBs of the seed affect   */
  79         /* only MSBs of the array mt[].                        */
  80         /* 2002/01/09 modified by Makoto Matsumoto             */
  81         mt->mt[mti] &= 0xffffffffUL;
  82         /* for >32 bit machines */
  83     }
  84     mt->mti = mti;
  85 }
  86 
  87 /* initialize by an array with array-length */
  88 /* init_key is the array for initializing keys */
  89 /* key_length is its length */
  90 void Scm_MTInitByArray(ScmMersenneTwister *mt,
  91                        ScmInt32 init_key[],
  92                        unsigned long key_length)
  93 {
  94     int i, j, k;
  95     Scm_MTInitByUI(mt, 19650218UL);
  96     i=1; j=0;
  97     k = (N>key_length ? N : key_length);
  98     for (; k; k--) {
  99         mt->mt[i] = (mt->mt[i] ^ ((mt->mt[i-1] ^ (mt->mt[i-1] >> 30)) * 1664525UL))
 100             + init_key[j] + j; /* non linear */
 101         mt->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
 102         i++; j++;
 103         if (i>=N) { mt->mt[0] = mt->mt[N-1]; i=1; }
 104         if (j>=key_length) j=0;
 105     }
 106     for (k=N-1; k; k--) {
 107         mt->mt[i] = (mt->mt[i] ^ ((mt->mt[i-1] ^ (mt->mt[i-1] >> 30)) * 1566083941UL))
 108             - i; /* non linear */
 109         mt->mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
 110         i++;
 111         if (i>=N) { mt->mt[0] = mt->mt[N-1]; i=1; }
 112     }
 113 
 114     mt->mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
 115 }
 116 
 117 /* generates a random number on [0,0xffffffff]-interval */
 118 inline unsigned long Scm_MTGenrandU32(ScmMersenneTwister *mt)
 119 {
 120     unsigned long y;
 121     int mti = mt->mti;
 122     static unsigned long mag01[2]={0x0UL, MATRIX_A};
 123     /* mag01[x] = x * MATRIX_A  for x=0,1 */
 124 
 125     if (mti >= N) { /* generate N words at one time */
 126         int kk;
 127 
 128         if (mti == N+1)   /* if Scm_MTInitByUI() has not been called, */
 129             Scm_MTInitByUI(mt, 5489UL); /* a default initial seed is used */
 130 
 131         for (kk=0;kk<N-M;kk++) {
 132             y = (mt->mt[kk]&UPPER_MASK)|(mt->mt[kk+1]&LOWER_MASK);
 133             mt->mt[kk] = mt->mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
 134         }
 135         for (;kk<N-1;kk++) {
 136             y = (mt->mt[kk]&UPPER_MASK)|(mt->mt[kk+1]&LOWER_MASK);
 137             mt->mt[kk] = mt->mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
 138         }
 139         y = (mt->mt[N-1]&UPPER_MASK)|(mt->mt[0]&LOWER_MASK);
 140         mt->mt[N-1] = mt->mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
 141 
 142         mti = 0;
 143     }
 144   
 145     y = mt->mt[mti++];
 146 
 147     /* Tempering */
 148     y ^= (y >> 11);
 149     y ^= (y << 7) & 0x9d2c5680UL;
 150     y ^= (y << 15) & 0xefc60000UL;
 151     y ^= (y >> 18);
 152 
 153     mt->mti = mti;
 154     return y;
 155 }
 156 
 157 /* generates a random number on (0,1) or [0,1) -real-interval */
 158 float Scm_MTGenrandF32(ScmMersenneTwister *mt, int exclude0)
 159 {
 160     float r;
 161     do {
 162         r = (float)(Scm_MTGenrandU32(mt)*(1.0/4294967296.0));
 163         /* divided by 2^32 */
 164     } while (exclude0 && r == 0.0); /*if we get 0.0, try another one. */;
 165     return r;
 166 }
 167 
 168 /* generates a random number on (0,1) or [0,1) with 53-bit resolution*/
 169 double Scm_MTGenrandF64(ScmMersenneTwister *mt, int exclude0)
 170 {
 171     double r;
 172     unsigned long a, b;
 173     do {
 174         a = Scm_MTGenrandU32(mt)>>5;
 175         b = Scm_MTGenrandU32(mt)>>6;
 176         r = (a*67108864.0+b)*(1.0/9007199254740992.0);
 177     } while (exclude0 && r == 0.0); /*if we get 0.0, try another one. */;
 178     return r;
 179 } 
 180 
 181 /*
 182  * Generic integer routine for [0, n-1], 0 < n <= 2^32
 183  */
 184 
 185 /* if integer N is 2^e, returns e; otherwise, returns -1. */
 186 static inline int xlog2(unsigned long n)
 187 {
 188 #if SIZEOF_LONG == 4
 189 # define START_BIT 16
 190 # define MAX_BIT 31
 191 #else /* assume sizeof(long) == 8 */
 192 # define START_BIT 32
 193 # define MAX_BIT 63
 194 #endif
 195     int e = START_BIT;
 196     unsigned long m = (1UL<<START_BIT);
 197 
 198     if (n < m) {
 199         do {
 200             m >>= 1;
 201             e--;
 202             if (n == m) return e;
 203         } while (e >= 0 && n < m);
 204     } else if (n > m) {
 205         do {
 206             m <<= 1;
 207             e++;
 208             if (n == m) return e;
 209         } while (e < MAX_BIT && n > m);
 210     } else { /* n == m */
 211         return e;
 212     }
 213     return -1;
 214 #undef START_BIT
 215 #undef MAX_BIT
 216 }
 217 
 218 
 219 /* generates a random number on [0,n-1], n < 2^32. */
 220 static ScmObj genrand_int_small(ScmMersenneTwister *mt, unsigned long n)
 221 {
 222     int e;
 223     unsigned long r;
 224     if ((e = xlog2(n)) == 0) {
 225         return SCM_MAKE_INT(0);
 226     } else if (e > 0) {
 227         /* optimize for 2^e case */
 228         r = Scm_MTGenrandU32(mt);
 229         if (e == 32) return Scm_MakeIntegerFromUI(r);
 230         else return Scm_MakeIntegerFromUI(r >> (32-e));
 231     } else {
 232         double q = floor((double)0xffffffff / (double)n);
 233         double qn = q * n;
 234         do {
 235             r = Scm_MTGenrandU32(mt);
 236         } while (r >= qn);
 237         return Scm_MakeIntegerFromUI((unsigned long)(r/q));
 238     }
 239 }
 240 
 241 ScmObj Scm_MTGenrandInt(ScmMersenneTwister *mt, ScmObj n)
 242 {
 243     if (SCM_INTP(n)) {
 244         long m = SCM_INT_VALUE(n);
 245         if (m <= 0) goto err;
 246         return genrand_int_small(mt, m);
 247     }
 248 #if SIZEOF_LONG == 4
 249     if (SCM_BIGNUMP(n)) {
 250         if (SCM_BIGNUM_SIGN(n) <= 0) goto err;
 251         if (SCM_BIGNUM_SIZE(n) == 1) {
 252             return genrand_int_small(mt, SCM_BIGNUM(n)->values[0]);
 253         }
 254         if (SCM_BIGNUM_SIZE(n) == 2
 255             && SCM_BIGNUM(n)->values[0] == 0
 256             && SCM_BIGNUM(n)->values[1] == 1) {
 257             return Scm_MakeIntegerFromUI(Scm_MTGenrandU32(mt));
 258         }
 259     }
 260 #endif
 261   err:
 262     Scm_Error("bad type of argument for n: positive integer up to 2^32 is required, but got %S", n);
 263     return SCM_UNDEFINED; /*dummy*/
 264 }
 265 
 266 /*
 267  * Gauche specific stuff
 268  */
 269 static ScmObj key_seed;
 270 static ScmObj mt_allocate(ScmClass *klass, ScmObj initargs);
 271 SCM_DEFINE_BUILTIN_CLASS(Scm_MersenneTwisterClass,
 272                          NULL, NULL, NULL, mt_allocate,
 273                          NULL);
 274 
 275 static ScmObj mt_allocate(ScmClass *klass, ScmObj initargs)
 276 {
 277     ScmObj seed = Scm_GetKeyword(key_seed, initargs, SCM_FALSE);
 278     ScmMersenneTwister *mt;
 279     
 280     if (!SCM_FALSEP(seed) && !SCM_EXACTP(seed) && !SCM_U32VECTORP(seed)) {
 281         Scm_Error("seed needs to be an exact integer or a u32vector, but got: %S", seed);
 282     }
 283     
 284     mt = SCM_NEW(ScmMersenneTwister);
 285     SCM_SET_CLASS(mt, &Scm_MersenneTwisterClass);
 286     mt->mti = N+1;
 287     if (SCM_EXACTP(seed)) {
 288         Scm_MTInitByUI(mt, Scm_GetUInteger(seed));
 289     } else if (SCM_U32VECTORP(seed)) {
 290         Scm_MTInitByArray(mt, (ScmInt32*)SCM_U32VECTOR_ELEMENTS(seed),
 291                           SCM_U32VECTOR_SIZE(seed));
 292     }
 293     return SCM_OBJ(mt);
 294 }
 295 
 296 extern void Scm_Init_mt_lib(ScmModule*);
 297 
 298 void Scm_Init_mt_random(void)
 299 {
 300     ScmModule *mod = SCM_FIND_MODULE("math.mt-random", SCM_FIND_MODULE_CREATE);
 301     SCM_INIT_EXTENSION(mtrandom);
 302     Scm_InitStaticClass(&Scm_MersenneTwisterClass, "<mersenne-twister>",
 303                         mod, NULL, 0);
 304     key_seed = SCM_MAKE_KEYWORD("seed");
 305     Scm_Init_mt_lib(mod);
 306 }
 307 

/* [<][>][^][v][top][bottom][index][help] */