home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / c / 11805 < prev    next >
Encoding:
Internet Message Format  |  1992-07-31  |  2.1 KB

  1. Xref: sparky comp.lang.c:11805 comp.sys.amiga.programmer:11849
  2. Newsgroups: comp.lang.c,comp.sys.amiga.programmer
  3. Path: sparky!uunet!email!hp
  4. From: hp@vmars.tuwien.ac.at (Peter Holzer)
  5. Subject: Re: Matt Dillon's DICE (Amiga C) and rand() function
  6. Message-ID: <1992Jul31.112751.6735@email.tuwien.ac.at>
  7. Sender: news@email.tuwien.ac.at
  8. Nntp-Posting-Host: quasi.vmars.tuwien.ac.at
  9. Organization: Technical University Vienna, Dept. for Realtime Systems, AUSTRIA
  10. References: <1992Jul29.081247.1@gallua> <1992Jul29.163704.26489@proxxi.se> <1992Jul30.214117.27748@athena.mit.edu>
  11. Date: Fri, 31 Jul 1992 11:27:51 GMT
  12. Lines: 39
  13.  
  14. scs@adam.mit.edu (Steve Summit) writes:
  15.  
  16. >To get integral random numbers with a different range, the
  17. >modulus operator is typically used:
  18.  
  19. >    rand() % n
  20.  
  21. >gives random numbers in the range 1..n-1 .  (Note that this
  22. >technique is slightly inaccurate, and works well only if RAND_MAX
  23. >is much greater than, or an exact multiple of, n).
  24.  
  25. Also, many implementations of rand (e.g. the one in BSD, and (I think)
  26. the example in the standard), have the property that they produce a
  27. cycle of length n if n is a divisor of RAND_MAX + 1. So rand % 2 will
  28. give you 0 and 1 alternately, which does not look very random. On
  29. systems, where RAND_MAX * n <= LONG_MAX, you can use 
  30.  
  31.     (long) rand() * n / (RAND_MAX + 1)
  32.  
  33. instead. On many 32bit systems this doesn't work however, and the
  34. portable solution is more complicated (The best I can come up with
  35. contains 3 multiplications, 3 additions and a lot of shifts). 
  36.  
  37. >One legitimate use of RAND_MAX is generating random floating-
  38. >point numbers; for example,
  39.  
  40. >    rand() / (double)(RAND_MAX - 1)
  41.  
  42. >should give randomly distributed numbers over the range 0..1 .
  43.  
  44. If you want a random value in the range [0, 1] you must divide by
  45. RAND_MAX, if you want a range of [0, 1), divide by (RAND_MAX + 1).
  46.  
  47.     Peter
  48. -- 
  49. |    _  | Peter J. Holzer                       | Think of it   |
  50. | |_|_) | Technical University Vienna           | as evolution  |
  51. | | |   | Dept. for Real-Time Systems           | in action!    |
  52. | __/   | hp@vmars.tuwien.ac.at                 |     Tony Rand |
  53.