_random.c
Upload User: gzelex
Upload Date: 2007-01-07
Package Size: 707k
Code Size: 17k
Development Platform:

MultiPlatform

  1. /*******************************************************************************
  2. +
  3. +  LEDA-R  3.2.3
  4. +
  5. +  _random.c
  6. +
  7. +  Copyright (c) 1995  by  Max-Planck-Institut fuer Informatik
  8. +  Im Stadtwald, 66123 Saarbruecken, Germany     
  9. +  All rights reserved.
  10. *******************************************************************************/
  11. // We use BSD Code for random, srandom, ...
  12. // modified by S. Naeher  (January 1995)
  13. /*
  14.  * Copyright (c) 1983 Regents of the University of California.
  15.  * All rights reserved.
  16.  *
  17.  * Redistribution and use in source and binary forms, with or without
  18.  * modification, are permitted provided that the following conditions
  19.  * are met:
  20.  * 1. Redistributions of source code must retain the above copyright
  21.  *    notice, this list of conditions and the following disclaimer.
  22.  * 2. Redistributions in binary form must reproduce the above copyright
  23.  *    notice, this list of conditions and the following disclaimer in the
  24.  *    documentation and/or other materials provided with the distribution.
  25.  * 3. All advertising materials mentioning features or use of this software
  26.  *    must display the following acknowledgement:
  27.  * This product includes software developed by the University of
  28.  * California, Berkeley and its contributors.
  29.  * 4. Neither the name of the University nor the names of its contributors
  30.  *    may be used to endorse or promote products derived from this software
  31.  *    without specific prior written permission.
  32.  *
  33.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  34.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  35.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  37.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  38.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  39.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  40.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  41.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  42.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  43.  * SUCH DAMAGE.
  44.  */
  45. #include <stdio.h>
  46. typedef unsigned int u_int;
  47. /* currently nod used
  48. static char*          bsd_initstate(u_int, char*, int);
  49. static char*          bsd_setstate(char*);
  50. */
  51. static unsigned long  bsd_random();
  52. /*
  53.  * random.c:
  54.  *
  55.  * An improved random number generation package.  In addition to the standard
  56.  * rand()/srand() like interface, this package also has a special state info
  57.  * interface.  The initstate() routine is called with a seed, an array of
  58.  * bytes, and a count of how many bytes are being passed in; this array is
  59.  * then initialized to contain information for random number generation with
  60.  * that much state information.  Good sizes for the amount of state
  61.  * information are 32, 64, 128, and 256 bytes.  The state can be switched by
  62.  * calling the setstate() routine with the same array as was initiallized
  63.  * with initstate().  By default, the package runs with 128 bytes of state
  64.  * information and generates far better random numbers than a linear
  65.  * congruential generator.  If the amount of state information is less than
  66.  * 32 bytes, a simple linear congruential R.N.G. is used.
  67.  *
  68.  * Internally, the state information is treated as an array of longs; the
  69.  * zeroeth element of the array is the type of R.N.G. being used (small
  70.  * integer); the remainder of the array is the state information for the
  71.  * R.N.G.  Thus, 32 bytes of state information will give 7 longs worth of
  72.  * state information, which will allow a degree seven polynomial.  (Note:
  73.  * the zeroeth word of state information also has some other information
  74.  * stored in it -- see setstate() for details).
  75.  * 
  76.  * The random number generation technique is a linear feedback shift register
  77.  * approach, employing trinomials (since there are fewer terms to sum up that
  78.  * way).  In this approach, the least significant bit of all the numbers in
  79.  * the state table will act as a linear feedback shift register, and will
  80.  * have period 2^deg - 1 (where deg is the degree of the polynomial being
  81.  * used, assuming that the polynomial is irreducible and primitive).  The
  82.  * higher order bits will have longer periods, since their values are also
  83.  * influenced by pseudo-random carries out of the lower bits.  The total
  84.  * period of the generator is approximately deg*(2**deg - 1); thus doubling
  85.  * the amount of state information has a vast influence on the period of the
  86.  * generator.  Note: the deg*(2**deg - 1) is an approximation only good for
  87.  * large deg, when the period of the shift register is the dominant factor.
  88.  * With deg equal to seven, the period is actually much longer than the
  89.  * 7*(2**7 - 1) predicted by this formula.
  90.  */
  91. /*
  92.  * For each of the currently supported random number generators, we have a
  93.  * break value on the amount of state information (you need at least this
  94.  * many bytes of state info to support this random number generator), a degree
  95.  * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
  96.  * the separation between the two lower order coefficients of the trinomial.
  97.  */
  98. #define TYPE_0 0 /* linear congruential */
  99. #define BREAK_0 8
  100. #define DEG_0 0
  101. #define SEP_0 0
  102. #define TYPE_1 1 /* x**7 + x**3 + 1 */
  103. #define BREAK_1 32
  104. #define DEG_1 7
  105. #define SEP_1 3
  106. #define TYPE_2 2 /* x**15 + x + 1 */
  107. #define BREAK_2 64
  108. #define DEG_2 15
  109. #define SEP_2 1
  110. #define TYPE_3 3 /* x**31 + x**3 + 1 */
  111. #define BREAK_3 128
  112. #define DEG_3 31
  113. #define SEP_3 3
  114. #define TYPE_4 4 /* x**63 + x + 1 */
  115. #define BREAK_4 256
  116. #define DEG_4 63
  117. #define SEP_4 1
  118. /*
  119.  * Array versions of the above information to make code run faster --
  120.  * relies on fact that TYPE_i == i.
  121.  */
  122. #define MAX_TYPES 5 /* max number of types above */
  123. static int degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
  124. static int seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
  125. /*
  126.  * Initially, everything is set up as if from:
  127.  *
  128.  * initstate(1, &randtbl, 128);
  129.  *
  130.  * Note that this initialization takes advantage of the fact that srandom()
  131.  * advances the front and rear pointers 10*rand_deg times, and hence the
  132.  * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
  133.  * element of the state information, which contains info about the current
  134.  * position of the rear pointer is just
  135.  *
  136.  * MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
  137.  */
  138. static long randtbl[DEG_3 + 1] = {
  139. TYPE_3,
  140. 0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
  141. 0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd,
  142. 0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88,
  143. 0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc,
  144. 0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
  145. 0x27fb47b9,
  146. };
  147. /*
  148.  * fptr and rptr are two pointers into the state info, a front and a rear
  149.  * pointer.  These two pointers are always rand_sep places aparts, as they
  150.  * cycle cyclically through the state information.  (Yes, this does mean we
  151.  * could get away with just one pointer, but the code for random() is more
  152.  * efficient this way).  The pointers are left positioned as they would be
  153.  * from the call
  154.  *
  155.  * initstate(1, randtbl, 128);
  156.  *
  157.  * (The position of the rear pointer, rptr, is really 0 (as explained above
  158.  * in the initialization of randtbl) because the state table pointer is set
  159.  * to point to randtbl[1] (as explained below).
  160.  */
  161. static long *fptr = &randtbl[SEP_3 + 1];
  162. static long *rptr = &randtbl[1];
  163. /*
  164.  * The following things are the pointer to the state information table, the
  165.  * type of the current generator, the degree of the current polynomial being
  166.  * used, and the separation between the two pointers.  Note that for efficiency
  167.  * of random(), we remember the first location of the state information, not
  168.  * the zeroeth.  Hence it is valid to access state[-1], which is used to
  169.  * store the type of the R.N.G.  Also, we remember the last location, since
  170.  * this is more efficient than indexing every time to find the address of
  171.  * the last element to see if the front and rear pointers have wrapped.
  172.  */
  173. //static long *state = &randtbl[1];
  174. static long *state = 0;
  175. static int rand_type = TYPE_3;
  176. static int rand_deg = DEG_3;
  177. static int rand_sep = SEP_3;
  178. static long *end_ptr = &randtbl[DEG_3 + 1];
  179. /*
  180.  * srandom:
  181.  *
  182.  * Initialize the random number generator based on the given seed.  If the
  183.  * type is the trivial no-state-information type, just remember the seed.
  184.  * Otherwise, initializes state[] based on the given "seed" via a linear
  185.  * congruential generator.  Then, the pointers are set to known locations
  186.  * that are exactly rand_sep places apart.  Lastly, it cycles the state
  187.  * information a given number of times to get rid of any initial dependencies
  188.  * introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
  189.  * for default usage relies on values produced by this routine.
  190.  */
  191. static void bsd_srandom(u_int x)
  192. {
  193. register int i;
  194. // initialize static variables at first call (s.n.)
  195. // (should not be necessary, however, some c++ compilers ...)
  196.         if (state == 0)
  197.         { fptr = &randtbl[SEP_3 + 1];
  198.           rptr = &randtbl[1];
  199.           state = &randtbl[1];
  200.           rand_type = TYPE_3;
  201.           rand_deg = DEG_3;
  202.           rand_sep = SEP_3;
  203.           end_ptr = &randtbl[DEG_3 + 1];
  204.          }
  205. state[0] = x;
  206. if (rand_type != TYPE_0)
  207. {   state[0] = x;
  208. for (i = 1; i < rand_deg; i++)
  209. state[i] = 1103515245 * state[i - 1] + 12345;
  210. fptr = &state[rand_sep];
  211. rptr = &state[0];
  212. for (i = 0; i < 10 * rand_deg; i++)
  213. (void)bsd_random();
  214. }
  215. }
  216. /*
  217.  * initstate:
  218.  *
  219.  * Initialize the state information in the given array of n bytes for future
  220.  * random number generation.  Based on the number of bytes we are given, and
  221.  * the break values for the different R.N.G.'s, we choose the best (largest)
  222.  * one we can and set things up for it.  srandom() is then called to
  223.  * initialize the state information.
  224.  * 
  225.  * Note that on return from srandom(), we set state[-1] to be the type
  226.  * multiplexed with the current value of the rear pointer; this is so
  227.  * successive calls to initstate() won't lose this information and will be
  228.  * able to restart with setstate().
  229.  * 
  230.  * Note: the first thing we do is save the current state, if any, just like
  231.  * setstate() so that it doesn't matter when initstate is called.
  232.  *
  233.  * Returns a pointer to the old state.
  234.  */
  235. static char* bsd_initstate(u_int seed, char* arg_state, int n)
  236. {
  237. register char *ostate = (char *)(&state[-1]);
  238. if (rand_type == TYPE_0)
  239. state[-1] = rand_type;
  240. else
  241. state[-1] = MAX_TYPES * (rptr - state) + rand_type;
  242. if (n < BREAK_0) {
  243. (void)fprintf(stderr,
  244.     "random: not enough state (%d bytes); ignored.n", n);
  245. return 0;
  246. }
  247. if (n < BREAK_1) {
  248. rand_type = TYPE_0;
  249. rand_deg = DEG_0;
  250. rand_sep = SEP_0;
  251. } else if (n < BREAK_2) {
  252. rand_type = TYPE_1;
  253. rand_deg = DEG_1;
  254. rand_sep = SEP_1;
  255. } else if (n < BREAK_3) {
  256. rand_type = TYPE_2;
  257. rand_deg = DEG_2;
  258. rand_sep = SEP_2;
  259. } else if (n < BREAK_4) {
  260. rand_type = TYPE_3;
  261. rand_deg = DEG_3;
  262. rand_sep = SEP_3;
  263. } else {
  264. rand_type = TYPE_4;
  265. rand_deg = DEG_4;
  266. rand_sep = SEP_4;
  267. }
  268. state = &(((long *)arg_state)[1]); /* first location */
  269. end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */
  270. bsd_srandom(seed);
  271. if (rand_type == TYPE_0)
  272. state[-1] = rand_type;
  273. else
  274. state[-1] = MAX_TYPES*(rptr - state) + rand_type;
  275. return ostate;
  276. }
  277. /*
  278.  * setstate:
  279.  *
  280.  * Restore the state from the given state array.
  281.  *
  282.  * Note: it is important that we also remember the locations of the pointers
  283.  * in the current state information, and restore the locations of the pointers
  284.  * from the old state information.  This is done by multiplexing the pointer
  285.  * location into the zeroeth word of the state information.
  286.  *
  287.  * Note that due to the order in which things are done, it is OK to call
  288.  * setstate() with the same state as the current state.
  289.  *
  290.  * Returns a pointer to the old state information.
  291.  */
  292. static char* bsd_setstate(char* arg_state)
  293. {
  294. register long *new_state = (long *)arg_state;
  295. register int type = int(new_state[0] % MAX_TYPES);
  296. register int rear = int(new_state[0] / MAX_TYPES);
  297. char *ostate = (char *)(&state[-1]);
  298. if (rand_type == TYPE_0)
  299. state[-1] = rand_type;
  300. else
  301. state[-1] = MAX_TYPES * (rptr - state) + rand_type;
  302. switch(type) {
  303. case TYPE_0:
  304. case TYPE_1:
  305. case TYPE_2:
  306. case TYPE_3:
  307. case TYPE_4:
  308. rand_type = type;
  309. rand_deg = degrees[type];
  310. rand_sep = seps[type];
  311. break;
  312. default:
  313. (void)fprintf(stderr,
  314.     "random: state info corrupted; not changed.n");
  315. }
  316. state = &new_state[1];
  317. if (rand_type != TYPE_0) {
  318. rptr = &state[rear];
  319. fptr = &state[(rear + rand_sep) % rand_deg];
  320. }
  321. end_ptr = &state[rand_deg]; /* set end_ptr too */
  322. return ostate;
  323. }
  324. /*
  325.  * random:
  326.  *
  327.  * If we are using the trivial TYPE_0 R.N.G., just do the old linear
  328.  * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is
  329.  * the same in all the other cases due to all the global variables that have
  330.  * been set up.  The basic operation is to add the number at the rear pointer
  331.  * into the one at the front pointer.  Then both pointers are advanced to
  332.  * the next location cyclically in the table.  The value returned is the sum
  333.  * generated, reduced to 31 bits by throwing away the "least random" low bit.
  334.  *
  335.  * Note: the code takes advantage of the fact that both the front and
  336.  * rear pointers can't wrap on the same call by not testing the rear
  337.  * pointer if the front one has wrapped.
  338.  *
  339.  * Returns a 31-bit random number.
  340.  */
  341. static unsigned long bsd_random()
  342. {
  343. long i;
  344. if (rand_type == TYPE_0)
  345. i = state[0] = (state[0] * 1103515245 + 12345) & 0x7fffffff;
  346. else {
  347. *fptr += *rptr;
  348. i = (*fptr >> 1) & 0x7fffffff; /* chucking least random bit */
  349. if (++fptr >= end_ptr) {
  350. fptr = state;
  351. ++rptr;
  352. } else if (++rptr >= end_ptr)
  353. rptr = state;
  354. }
  355. return (unsigned long)i;
  356. }
  357. //------------------------------------------------------------------------------
  358. #include <LEDA/random.h>
  359. #include <time.h>
  360. //we assume that bsd_random() produces a 31 bit integer
  361. #define RANDMAX 0x7FFFFFFF
  362. /* we have:
  363.    the source is in bit mode iff bit_mode == true
  364.    in bit mode: pat = 2^{p+1} - 1 where p is the precision.
  365.    in integer mode: diff = high - low and 
  366.                     if diff > 0 then pat = 2^p - 1 where 
  367.                          p = 1 + lfloor log diff rfloor
  368.                     if diff = 0 then pat = 0
  369. */
  370. void random_source::set_seed(int seed) { bsd_srandom(seed); }
  371. random_source::random_source()
  372. { time_t seed;
  373.   time(&seed);
  374.   bsd_srandom(int(seed));
  375.   pat = 0xFFFFFFFF; 
  376.   bit_mode = true;
  377.   low = diff = 0;
  378.  }
  379. random_source::random_source(int bits) 
  380. { time_t seed;
  381.   time(&seed);
  382.   bsd_srandom(int(seed));
  383.   if (bits <= 0 || bits >= 32)
  384.      pat = 0xFFFFFFFF; 
  385.   else
  386.      pat = (1 << bits) - 1;
  387.   bit_mode = true;
  388.   low = diff = 0;
  389.  }
  390. void random_source::set_range(int l, int h)
  391. { low  = l;
  392.   diff = (h < l) ? 0 : h-l;
  393.   bit_mode = false;
  394.   pat = 1;
  395.   while (pat <= diff) pat <<= 1;
  396.   pat--;
  397.  }
  398. random_source::random_source(int l, int h) 
  399. { time_t seed;
  400.   time(&seed);
  401.   bsd_srandom(int(seed));
  402.   set_range(l,h);
  403.    }
  404. void random_source::set_precision(int bits) 
  405. { if (0 >= bits || bits >= 32)
  406.      pat = 0xFFFFFFFF; 
  407.   else
  408.      pat = (1 << bits) - 1;
  409.   bit_mode = true;
  410.  }
  411. unsigned random_source::get() { return unsigned(bsd_random()); }
  412. int random_source::operator()()
  413. { unsigned long x =  bsd_random() & pat;
  414.   if (bit_mode)
  415.      return int(x);
  416.   else
  417.     { while (x > diff) x = bsd_random() & pat;
  418.       return (int)(low + x);
  419.      }
  420.  }
  421. int  random_source::operator()(int bits)
  422. { return int(bsd_random() % ((1<<bits)-1)); }
  423. int  random_source::operator()(int l, int h)
  424. { if (h < l) return 0;
  425.   int  old_low = low;
  426.   int  old_diff = diff;
  427.   unsigned long  old_pat = pat;
  428.   bool old_bit_mode = bit_mode;
  429.   
  430.   set_range(l,h);
  431.   int x  = operator()();
  432.   low = old_low; 
  433.   diff = old_diff; 
  434.   pat = old_pat; 
  435.   bit_mode = old_bit_mode;
  436.   return x; 
  437. }
  438. random_source& random_source::operator>>(char& x)
  439. { x = char(operator()());
  440.   return *this;
  441.  }
  442. random_source& random_source::operator>>(int& x)      
  443. { x = int(operator()());
  444.   return *this;
  445.  }
  446. random_source& random_source::operator>>(long& x)      
  447. { x = long(operator()());
  448.   return *this;
  449.  }
  450. random_source& random_source::operator>>(unsigned char& x)
  451. { x = (unsigned char)(operator()());
  452.   return *this;
  453.  }
  454. random_source& random_source::operator>>(unsigned int& x)
  455. { x = (unsigned int)(operator()());
  456.   return *this;
  457.  }
  458. random_source& random_source::operator>>(unsigned long& x)
  459. { x = (unsigned long)(operator()());
  460.   return *this;
  461.  }
  462. #if defined(__BUILTIN_BOOL__)
  463. random_source& random_source::operator>>(bool& x)
  464. { x = bsd_random() & 1; 
  465.   return *this;
  466.  }
  467. #endif
  468. random_source& random_source::operator>>(float&  x)
  469. { x = float(bsd_random())/RANDMAX; 
  470.   return *this;
  471.  }
  472. random_source& random_source::operator>>(double& x)
  473. { x = float(bsd_random())/RANDMAX; 
  474.   return *this;
  475.  }
  476. // default random source
  477. random_source rand_int;