home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / INFO / MISC / RANDOMS.ZIP / RANDOM.PAS < prev   
Encoding:
Pascal/Delphi Source File  |  1988-10-31  |  2.1 KB  |  59 lines

  1. FUNCTION RANDOM: REAL;
  2.  
  3. {  This Turbo Pascal V4.0 function returns a REAL  pseudo-random  number
  4.    in the range:  0.0 < RANDOM() < 1.0
  5.  
  6.    The period of this function is  2,147,483,646 (2**31-2);  that is, it
  7.    will generate 2,147,483,636 pseudo-random  numbers  before  repeating
  8.    the series.
  9.  
  10.    Examples:
  11.                    X := 2.0*RANDOM()-1.0;
  12.                    IF RANDOM < 0.5 THEN LOWER;
  13.  
  14.    In the first example,  X is assigned a random  number  in  the  range
  15.    of:  -1.0 < X < +1.0.   In the second  example,  procedure  LOWER  is
  16.    called fifty percent of the time.  (i.e. When the value  returned  by
  17.    RANDOM is less than one-half.)
  18.  
  19.    Note:  SEED, the random number seed, MUST be declared as a  global
  20.           variable of type LONGINT  (i.e. An integer variable capable
  21.           of representing numbers as large as 2,147,483,647) and MUST
  22.           be initialized in the main procedure to  a  number  in  the
  23.           range:  0 < SEED < 2147483647  before  Function  RANDOM  is
  24.           invoked.   (Turbo Pascal allows this to  be  done  using  a
  25.           "typed constant" as in:  VAR  SEED: LONGINT = 1; )
  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. CONST
  40.   A = 16807;       { The multiplier.         }
  41.   M = 2147483647;  { The modulus = 2**31-1.  }
  42.   Q = 127773;      { Q = M DIV A             }
  43.   R = 2836;        { R = M MOD A             }
  44.  
  45. VAR
  46.   LO, HI, TEMP : LONGINT;
  47.  
  48. BEGIN
  49.   HI := SEED DIV Q;
  50.   LO := SEED MOD Q;
  51.   TEMP := A*LO - R*HI;
  52.   IF TEMP <= 0
  53.     THEN
  54.       SEED := TEMP + M
  55.     ELSE
  56.       SEED := TEMP;
  57.   RANDOM := SEED / M
  58. END { Function RANDOM };
  59.