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