home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!charon.amdahl.com!pacbell.com!mips!sdd.hp.com!uakari.primate.wisc.edu!ames!agate!linus!linus.mitre.org!truth!jrv
- From: jrv@truth.uucp (Vanzandt)
- Newsgroups: comp.lang.c
- Subject: Re: Scaled random number (Was: Matt Dillon's DICE (Amiga C) and rand() function)
- Message-ID: <1992Aug19.175913.29022@linus.mitre.org>
- Date: 19 Aug 92 17:59:13 GMT
- References: <4476@teslab.lab.oz.au>
- Sender: news@linus.mitre.org (News Service)
- Organization: The MITRE Corp., Bedford, Ma.
- Lines: 39
- Nntp-Posting-Host: truth.mitre.org
-
- In article <4476@teslab.lab.oz.au> andrew@teslab.lab.oz.au (Andrew Phillips) writes:
- >ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:
- >
- >: Suppose you want to generate integers in the range 0..N-1,
- >: with each integer being equally likely, and that you have
- >: a rand() function which delivers integers in the range 0..RANDMAX
- >: with each integer being equally likely.
- >: Then r%N will indeed give you integers in the range 0..N-1,
- >: but unless (RANDMAX+1)%N == 0, they will NOT be equally likely.
- >
- >The proper way is to use the most significant digits:
- >
- >#include <stdlib.h>
- >
- >#define RANDN(N) ((int)((rand()*(unsigned long)N)/(RAND_MAX+1)))
- >
- >Andrew Phillips (andrew@teslab.lab.oz.au) Phone +61 (Aust) 2 (Sydney) 287 6551
-
- The division still doesn't give _equally_likely_ integers. Suppose
- RAND_MAX==7, N==3, and r=rand(). We have the following 8 equally likely
- possibilities:
- r r*3/8
- 0 0
- 1 0
- 2 0
- 3 1
- 4 1
- 5 1
- 6 2
- 7 2
- ...so 0 is more likely than 2. I believe you must discard the original random
- number if r/N >= RAND_MAX/N, then you can use r%N or r*N/(RAND_MAX+1).
- If this is done in a function then three divisions, or else two divisions
- and a multiplication, are required. If it's done in the calling program
- and N doesn't change, then one of the divisions can be moved outside the loop.
-
- - Jim Van Zandt <jrv@mbunix.mitre.org>
-
- P.S. Should this be in the FAQ?
-