Path: utzoo!mnetor!uunet!seismo!sundc!pitstop!sun!decwrl!decvax!mcnc!gatech!bloom-beacon!husc6!linus!philabs!pwa-b!mmintl!franka From: franka@mmintl.UUCP (Frank Adams) Newsgroups: comp.lang.c Subject: Re: Random Numbers ... Message-ID: <2734@mmintl.UUCP> Date: 27 Feb 88 04:06:28 GMT References: <11972@brl-adm.ARPA> <7097@sol.ARPA> <5555@cit-vax.Caltech.Edu> Reply-To: franka@mmintl.UUCP (Frank Adams) Organization: Multimate International, E. Hartford, CT. Lines: 40 In article <5555@cit-vax.Caltech.Edu> wen-king@cit-vlsi.UUCP (Wen-King Su) writes: >In general, the correct way to do it is to use a random number generator >of an appropriate range (the smallest power of 2 that is large enough to >cover all the numbers you need). Then[:] > >unsigned my_random_source(); > >my_random(range) > int range; >{ > int value; > do { value = my_random_source(); } while(value >= range); > return(value); >} This is fine if 'range' is a reasonably large number. On the other hand, if it is 2, it works very badly. More generally, try: unsigned my_random_source(); int source_limit; my_random(range) int range; { int value; int multiplicity = source_limit / range; int limit = multiplicity * range do { value = my_random_source(); } while(value >= limit); return(value / multiplicity); } To be on the safe side, you could add a check for limit != 0. There are techniques for dealing with that case, but it is usually best to just increase the size of the numbers you are getting from the generator. -- Frank Adams ihnp4!philabs!pwa-b!mmintl!franka Ashton-Tate 52 Oakland Ave North E. Hartford, CT 06108