home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / INFO / MISC / RANDOMS.ZIP / RANDOM.C next >
Encoding:
Text File  |  1988-10-31  |  2.0 KB  |  60 lines

  1. double random()
  2.  
  3. /*
  4.    This Turbo C V1.5 function returns a double pseudo-random  number  in
  5.    the range:  0.0 < random() < 1.0
  6.  
  7.    The period of this function is  2,147,483,646 (2**31-2);  that is, it
  8.    will generate 2,147,483,636 pseudo-random  numbers  before  repeating
  9.    the series.
  10.  
  11.    Examples:
  12.                    x = 2.0*random()-1.0;
  13.                    if random < 0.5 lower;
  14.  
  15.    In the first example,  X is assigned a random  number  in  the  range
  16.    of:  -1.0 < X < +1.0.   In the second  example,  procedure  lower  is
  17.    called fifty percent of the time.  (i.e.  When the value returned  by
  18.    random is less than one-half.)
  19.  
  20.    Note:  The random number seed, "seed", MUST be declared as a global
  21.           variable of type  "long int".   (i.e.  An  integer  variable
  22.           capable of representing numbers as large  as  2,147,483,647)
  23.           and MUST be initialized in the main procedure to  a  number
  24.           in the range:  0 < seed < 2147483647  before this  function
  25.           is invoked.
  26.  
  27.    This function is based on a Pascal routine  given  in  the  following
  28.      reference:
  29.  
  30.    Park, Stephen K.,  &  Miller, Keith W.,  "Random  Number  Generators:
  31.    Good Ones are Hard to Find", in "Communications of the ACM", Vol. 31,
  32.    No. 10  (October 1988),  pp 1192 - 1201.    Abstract:  "Practical and
  33.    theoretical issues are presented concerning the  design,  implementa-
  34.    tion,  and use of a good,  minimal standard random  number  generator
  35.    that will port to virtually all systems."
  36.  
  37.    Function coded by Harry M. Murphy on 31 October 1988. */
  38.  
  39. {
  40.       /* A = the multiplier.
  41.          M = the modulus = 2^31-1
  42.          Q = M / A
  43.          R = M % A */
  44.  
  45. #define  A 16807
  46. #define  M 2147483647
  47. #define  Q 127773
  48. #define  R 2836
  49.  
  50. long int lo, hi, temp;
  51.  
  52.         hi = seed / Q;
  53.         lo = seed % Q;
  54.         temp = A*lo - R*hi;
  55.         if (temp <= 0)
  56.                 seed = temp + M;
  57.         else
  58.                 seed = temp;
  59.         return (double) seed / M; }
  60.