home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / bsd_srcs / usr.bin / lisp / lispnews / text0047.txt < prev    next >
Encoding:
Internet Message Format  |  1985-11-10  |  1.2 KB

  1. Date: 29-Nov-82 15:56:09-PST (Mon)
  2. From: alice!sola!mitch
  3. Subject: Random Numbers in Franz
  4. To: alice!ucbvax!franz-friends
  5.  
  6. In general, it is very bad practice to compute a random number between 0
  7. and n by any expression such as (mod (random) n).  In fact, Franz's
  8. random function does exactly that, returning the number generated by the
  9. C function rand(3) modulo n.  This technique uses only the rightmost 
  10. bits of successive calls to rand, and the righmost n bits of congruential
  11. sequences (like that returned by rand(3)) have a period of AT MOST 2**n
  12. (See Knuth vol.2 p. 12).  So using the rightmost two bits will indeed give
  13. you sequences of at most period 4.  (If your lisp doesn't have this 
  14. behavior, you're not using the standard rand.)
  15.  
  16. A better way to do it is to use the high order bits, by dividing the entire
  17. range up into n pieces and then seeing where you fall.  (This method is
  18. biased if n is of the same order as the range, though.)
  19.  
  20. The code I use is:
  21.  
  22.  
  23. (or (getd '$old-random) (putd '$old-random (getd 'random)))
  24.  
  25. (defun random n
  26.   (cond ((eq n 0) ($old-random))
  27.     ((fix (quotient (boole 1 ($old-random) #o 7777777777)
  28.             (quotient #o 7777777777 (arg 1)))))))
  29.  
  30.         Mitch Marcus
  31.  
  32.  
  33.  
  34.  
  35.  
  36.