home *** CD-ROM | disk | FTP | other *** search
/ Amiga ISO Collection / AmigaUtilCD2.iso / Programming / GCC / GERLIB_DEV08B.LHA / gerlib / amiga / normal / random.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-12-12  |  13.4 KB  |  401 lines

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