home *** CD-ROM | disk | FTP | other *** search
/ The CDPD Public Domain Collection for CDTV 3 / CDPDIII.bin / pd / programming / gnuc / gen_library / rcs / random.c,v < prev    next >
Encoding:
Text File  |  1992-07-04  |  13.2 KB  |  407 lines

  1. head    1.1;
  2. access;
  3. symbols
  4.     version39-41:1.1;
  5. locks;
  6. comment    @ * @;
  7.  
  8.  
  9. 1.1
  10. date    92.06.08.18.31.20;    author mwild;    state Exp;
  11. branches;
  12. next    ;
  13.  
  14.  
  15. desc
  16. @initial checkin
  17. @
  18.  
  19.  
  20. 1.1
  21. log
  22. @Initial revision
  23. @
  24. text
  25. @/*
  26.  * Copyright (c) 1983 Regents of the University of California.
  27.  * All rights reserved.
  28.  *
  29.  * Redistribution and use in source and binary forms are permitted
  30.  * provided that: (1) source distributions retain this entire copyright
  31.  * notice and comment, and (2) distributions including binaries display
  32.  * the following acknowledgement:  ``This product includes software
  33.  * developed by the University of California, Berkeley and its contributors''
  34.  * in the documentation or other materials provided with the distribution
  35.  * and in all advertising materials mentioning features or use of this
  36.  * software. Neither the name of the University nor the names of its
  37.  * contributors may be used to endorse or promote products derived
  38.  * from this software without specific prior written permission.
  39.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  40.  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  41.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  42.  */
  43.  
  44. #if defined(LIBC_SCCS) && !defined(lint)
  45. static char sccsid[] = "@@(#)random.c    5.7 (Berkeley) 6/1/90";
  46. #endif /* LIBC_SCCS and not lint */
  47.  
  48. #define KERNEL
  49. #include "ixemul.h"
  50.  
  51. /* ATTENTION: there are quite a few static variables in here that will
  52.  *            during execution. But since this is a random-number generator,
  53.  *          this can only make for better random-results ;-)) */
  54.  
  55. /*
  56.  * random.c:
  57.  * An improved random number generation package.  In addition to the standard
  58.  * rand()/srand() like interface, this package also has a special state info
  59.  * interface.  The initstate() routine is called with a seed, an array of
  60.  * bytes, and a count of how many bytes are being passed in; this array is then
  61.  * initialized to contain information for random number generation with that
  62.  * much state information.  Good sizes for the amount of state information are
  63.  * 32, 64, 128, and 256 bytes.  The state can be switched by calling the
  64.  * setstate() routine with the same array as was initiallized with initstate().
  65.  * By default, the package runs with 128 bytes of state information and
  66.  * generates far better random numbers than a linear congruential generator.
  67.  * If the amount of state information is less than 32 bytes, a simple linear
  68.  * congruential R.N.G. is used.
  69.  * Internally, the state information is treated as an array of longs; the
  70.  * zeroeth element of the array is the type of R.N.G. being used (small
  71.  * integer); the remainder of the array is the state information for the
  72.  * R.N.G.  Thus, 32 bytes of state information will give 7 longs worth of
  73.  * state information, which will allow a degree seven polynomial.  (Note: the 
  74.  * zeroeth word of state information also has some other information stored
  75.  * in it -- see setstate() for details).
  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 have
  80.  * period 2^deg - 1 (where deg is the degree of the polynomial being used,
  81.  * assuming that the polynomial is irreducible and primitive).  The higher
  82.  * order bits will have longer periods, since their values are also influenced
  83.  * by pseudo-random carries out of the lower bits.  The total period of the
  84.  * generator is approximately deg*(2**deg - 1); thus doubling the amount of
  85.  * state information has a vast influence on the period of the generator.
  86.  * Note: the deg*(2**deg - 1) is an approximation only good for large deg,
  87.  * when the period of the shift register is the dominant factor.  With deg
  88.  * equal to seven, the period is actually much longer than the 7*(2**7 - 1)
  89.  * predicted by this formula.
  90.  */
  91.  
  92.  
  93.  
  94. /*
  95.  * For each of the currently supported random number generators, we have a
  96.  * break value on the amount of state information (you need at least this
  97.  * many bytes of state info to support this random number generator), a degree
  98.  * for the polynomial (actually a trinomial) that the R.N.G. is based on, and
  99.  * the separation between the two lower order coefficients of the trinomial.
  100.  */
  101.  
  102. #define        TYPE_0        0        /* linear congruential */
  103. #define        BREAK_0        8
  104. #define        DEG_0        0
  105. #define        SEP_0        0
  106.  
  107. #define        TYPE_1        1        /* x**7 + x**3 + 1 */
  108. #define        BREAK_1        32
  109. #define        DEG_1        7
  110. #define        SEP_1        3
  111.  
  112. #define        TYPE_2        2        /* x**15 + x + 1 */
  113. #define        BREAK_2        64
  114. #define        DEG_2        15
  115. #define        SEP_2        1
  116.  
  117. #define        TYPE_3        3        /* x**31 + x**3 + 1 */
  118. #define        BREAK_3        128
  119. #define        DEG_3        31
  120. #define        SEP_3        3
  121.  
  122. #define        TYPE_4        4        /* x**63 + x + 1 */
  123. #define        BREAK_4        256
  124. #define        DEG_4        63
  125. #define        SEP_4        1
  126.  
  127.  
  128. /*
  129.  * Array versions of the above information to make code run faster -- relies
  130.  * on fact that TYPE_i == i.
  131.  */
  132.  
  133. #define        MAX_TYPES    5        /* max number of types above */
  134.  
  135. static  int        degrees[ MAX_TYPES ]    = { DEG_0, DEG_1, DEG_2,
  136.                                 DEG_3, DEG_4 };
  137.  
  138. static  int        seps[ MAX_TYPES ]    = { SEP_0, SEP_1, SEP_2,
  139.                                 SEP_3, SEP_4 };
  140.  
  141.  
  142.  
  143. /*
  144.  * Initially, everything is set up as if from :
  145.  *        initstate( 1, &randtbl, 128 );
  146.  * Note that this initialization takes advantage of the fact that srandom()
  147.  * advances the front and rear pointers 10*rand_deg times, and hence the
  148.  * rear pointer which starts at 0 will also end up at zero; thus the zeroeth
  149.  * element of the state information, which contains info about the current
  150.  * position of the rear pointer is just
  151.  *    MAX_TYPES*(rptr - state) + TYPE_3 == TYPE_3.
  152.  */
  153.  
  154. static  long        randtbl[ DEG_3 + 1 ]    = { TYPE_3,
  155.                 0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 
  156.                 0xde3b81e0, 0xdf0a6fb5, 0xf103bc02, 0x48f340fb, 
  157.                 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd, 
  158.                 0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 
  159.                 0xda672e2a, 0x1588ca88, 0xe369735d, 0x904f35f7, 
  160.                 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc, 
  161.                 0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 
  162.                     0xf5ad9d0e, 0x8999220b, 0x27fb47b9 };
  163.  
  164. /*
  165.  * fptr and rptr are two pointers into the state info, a front and a rear
  166.  * pointer.  These two pointers are always rand_sep places aparts, as they cycle
  167.  * cyclically through the state information.  (Yes, this does mean we could get
  168.  * away with just one pointer, but the code for random() is more efficient this
  169.  * way).  The pointers are left positioned as they would be from the call
  170.  *            initstate( 1, randtbl, 128 )
  171.  * (The position of the rear pointer, rptr, is really 0 (as explained above
  172.  * in the initialization of randtbl) because the state table pointer is set
  173.  * to point to randtbl[1] (as explained below).
  174.  */
  175.  
  176. static  long        *fptr            = &randtbl[ SEP_3 + 1 ];
  177. static  long        *rptr            = &randtbl[ 1 ];
  178.  
  179.  
  180.  
  181. /*
  182.  * The following things are the pointer to the state information table,
  183.  * the type of the current generator, the degree of the current polynomial
  184.  * being used, and the separation between the two pointers.
  185.  * Note that for efficiency of random(), we remember the first location of
  186.  * the state information, not the zeroeth.  Hence it is valid to access
  187.  * state[-1], which is used to store the type of the R.N.G.
  188.  * Also, we remember the last location, since this is more efficient than
  189.  * indexing every time to find the address of the last element to see if
  190.  * the front and rear pointers have wrapped.
  191.  */
  192.  
  193. static  long        *state            = &randtbl[ 1 ];
  194.  
  195. static  int        rand_type        = TYPE_3;
  196. static  int        rand_deg        = DEG_3;
  197. static  int        rand_sep        = SEP_3;
  198.  
  199. static  long        *end_ptr        = &randtbl[ DEG_3 + 1 ];
  200.  
  201.  
  202.  
  203. /*
  204.  * srandom:
  205.  * Initialize the random number generator based on the given seed.  If the
  206.  * type is the trivial no-state-information type, just remember the seed.
  207.  * Otherwise, initializes state[] based on the given "seed" via a linear
  208.  * congruential generator.  Then, the pointers are set to known locations
  209.  * that are exactly rand_sep places apart.  Lastly, it cycles the state
  210.  * information a given number of times to get rid of any initial dependencies
  211.  * introduced by the L.C.R.N.G.
  212.  * Note that the initialization of randtbl[] for default usage relies on
  213.  * values produced by this routine.
  214.  */
  215.  
  216. srandom( x )
  217.  
  218.     unsigned        x;
  219. {
  220.         register  int        i, j;
  221.     long random();
  222.  
  223.     if(  rand_type  ==  TYPE_0  )  {
  224.         state[ 0 ] = x;
  225.     }
  226.     else  {
  227.         j = 1;
  228.         state[ 0 ] = x;
  229.         for( i = 1; i < rand_deg; i++ )  {
  230.         state[i] = 1103515245*state[i - 1] + 12345;
  231.         }
  232.         fptr = &state[ rand_sep ];
  233.         rptr = &state[ 0 ];
  234.         for( i = 0; i < 10*rand_deg; i++ )  random();
  235.     }
  236. }
  237.  
  238.  
  239.  
  240. /*
  241.  * initstate:
  242.  * Initialize the state information in the given array of n bytes for
  243.  * future random number generation.  Based on the number of bytes we
  244.  * are given, and the break values for the different R.N.G.'s, we choose
  245.  * the best (largest) one we can and set things up for it.  srandom() is
  246.  * then called to initialize the state information.
  247.  * Note that on return from srandom(), we set state[-1] to be the type
  248.  * multiplexed with the current value of the rear pointer; this is so
  249.  * successive calls to initstate() won't lose this information and will
  250.  * be able to restart with setstate().
  251.  * Note: the first thing we do is save the current state, if any, just like
  252.  * setstate() so that it doesn't matter when initstate is called.
  253.  * Returns a pointer to the old state.
  254.  */
  255.  
  256. char  *
  257. initstate( seed, arg_state, n )
  258.  
  259.     unsigned        seed;            /* seed for R. N. G. */
  260.     char        *arg_state;        /* pointer to state array */
  261.     int            n;            /* # bytes of state info */
  262. {
  263.     register  char        *ostate        = (char *)( &state[ -1 ] );
  264.  
  265.     if(  rand_type  ==  TYPE_0  )  state[ -1 ] = rand_type;
  266.     else  state[ -1 ] = MAX_TYPES*(rptr - state) + rand_type;
  267.     if(  n  <  BREAK_1  )  {
  268.         if(  n  <  BREAK_0  )  {
  269. #if 0
  270.         fprintf( stderr, "initstate: not enough state (%d bytes); ignored.\n", n );
  271. #else
  272.         ix_panic ("initstate: not enough state; ignored.");
  273. #endif
  274.         return 0;
  275.         }
  276.         rand_type = TYPE_0;
  277.         rand_deg = DEG_0;
  278.         rand_sep = SEP_0;
  279.     }
  280.     else  {
  281.         if(  n  <  BREAK_2  )  {
  282.         rand_type = TYPE_1;
  283.         rand_deg = DEG_1;
  284.         rand_sep = SEP_1;
  285.         }
  286.         else  {
  287.         if(  n  <  BREAK_3  )  {
  288.             rand_type = TYPE_2;
  289.             rand_deg = DEG_2;
  290.             rand_sep = SEP_2;
  291.         }
  292.         else  {
  293.             if(  n  <  BREAK_4  )  {
  294.             rand_type = TYPE_3;
  295.             rand_deg = DEG_3;
  296.             rand_sep = SEP_3;
  297.             }
  298.             else  {
  299.             rand_type = TYPE_4;
  300.             rand_deg = DEG_4;
  301.             rand_sep = SEP_4;
  302.             }
  303.         }
  304.         }
  305.     }
  306.     state = &(  ( (long *)arg_state )[1]  );    /* first location */
  307.     end_ptr = &state[ rand_deg ];    /* must set end_ptr before srandom */
  308.     srandom( seed );
  309.     if(  rand_type  ==  TYPE_0  )  state[ -1 ] = rand_type;
  310.     else  state[ -1 ] = MAX_TYPES*(rptr - state) + rand_type;
  311.     return( ostate );
  312. }
  313.  
  314.  
  315.  
  316. /*
  317.  * setstate:
  318.  * Restore the state from the given state array.
  319.  * Note: it is important that we also remember the locations of the pointers
  320.  * in the current state information, and restore the locations of the pointers
  321.  * from the old state information.  This is done by multiplexing the pointer
  322.  * location into the zeroeth word of the state information.
  323.  * Note that due to the order in which things are done, it is OK to call
  324.  * setstate() with the same state as the current state.
  325.  * Returns a pointer to the old state information.
  326.  */
  327.  
  328. char  *
  329. setstate( arg_state )
  330.  
  331.     char        *arg_state;
  332. {
  333.     register  long        *new_state    = (long *)arg_state;
  334.     register  int        type        = new_state[0]%MAX_TYPES;
  335.     register  int        rear        = new_state[0]/MAX_TYPES;
  336.     char            *ostate        = (char *)( &state[ -1 ] );
  337.  
  338.     if(  rand_type  ==  TYPE_0  )  state[ -1 ] = rand_type;
  339.     else  state[ -1 ] = MAX_TYPES*(rptr - state) + rand_type;
  340.     switch(  type  )  {
  341.         case  TYPE_0:
  342.         case  TYPE_1:
  343.         case  TYPE_2:
  344.         case  TYPE_3:
  345.         case  TYPE_4:
  346.         rand_type = type;
  347.         rand_deg = degrees[ type ];
  348.         rand_sep = seps[ type ];
  349.         break;
  350.  
  351.         default:
  352. #if 0
  353.         fprintf( stderr, "setstate: state info has been munged; not changed.\n" );
  354. #else
  355.         ix_panic ("setstate: state info has been munged; not changed.");
  356. #endif
  357.     }
  358.     state = &new_state[ 1 ];
  359.     if(  rand_type  !=  TYPE_0  )  {
  360.         rptr = &state[ rear ];
  361.         fptr = &state[ (rear + rand_sep)%rand_deg ];
  362.     }
  363.     end_ptr = &state[ rand_deg ];        /* set end_ptr too */
  364.     return( ostate );
  365. }
  366.  
  367.  
  368.  
  369. /*
  370.  * random:
  371.  * If we are using the trivial TYPE_0 R.N.G., just do the old linear
  372.  * congruential bit.  Otherwise, we do our fancy trinomial stuff, which is the
  373.  * same in all ther other cases due to all the global variables that have been
  374.  * set up.  The basic operation is to add the number at the rear pointer into
  375.  * the one at the front pointer.  Then both pointers are advanced to the next
  376.  * location cyclically in the table.  The value returned is the sum generated,
  377.  * reduced to 31 bits by throwing away the "least random" low bit.
  378.  * Note: the code takes advantage of the fact that both the front and
  379.  * rear pointers can't wrap on the same call by not testing the rear
  380.  * pointer if the front one has wrapped.
  381.  * Returns a 31-bit random number.
  382.  */
  383.  
  384. long
  385. random()
  386. {
  387.     long        i;
  388.     
  389.     if(  rand_type  ==  TYPE_0  )  {
  390.         i = state[0] = ( state[0]*1103515245 + 12345 )&0x7fffffff;
  391.     }
  392.     else  {
  393.         *fptr += *rptr;
  394.         i = (*fptr >> 1)&0x7fffffff;    /* chucking least random bit */
  395.         if(  ++fptr  >=  end_ptr  )  {
  396.         fptr = state;
  397.         ++rptr;
  398.         }
  399.         else  {
  400.         if(  ++rptr  >=  end_ptr  )  rptr = state;
  401.         }
  402.     }
  403.     return( i );
  404. }
  405.  
  406. @
  407.