home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.lang.c:11800 comp.sys.amiga.programmer:11845
- Path: sparky!uunet!overload!dillon
- From: dillon@overload.Berkeley.CA.US (Matthew Dillon)
- Newsgroups: comp.lang.c,comp.sys.amiga.programmer
- Subject: Re: Matt Dillon's DICE (Amiga C) and rand() function
- Distribution: world
- Message-ID: <dillon.0kbn@overload.Berkeley.CA.US>
- References: <1992Jul29.081247.1@gallua> <1992Jul29.163704.26489@proxxi.se>
- Date: 30 Jul 92 22:57:34 PST
- Organization: Not an Organization
- Lines: 55
-
- In article <1992Jul29.163704.26489@proxxi.se> elias@proxxi.se (Elias M}rtensson (proxxi)) writes:
- >CADS_COLE@GALLUA.BITNET (Kevin Cole; Washington DC) writes:
- >
- >>Date Sent: 29-Jul-1992 08:09:36
- >
- >>Greetings from the void,
- >
- >>Here's a very short C program that doesn't do what the documentation claims.
- >>According to Matt Dillon's DICE documents, I can limit the range of values
- >>Thanx.
- >
- >> #include <stdio.h>
- >> #include <stdlib.h>
- >> #define RAND_MAX ((1023))
- >> main()
- >> {
- >> int i;
- >> for (;;)
- >> {
- >> i = rand();
- >> printf("Random number %04X (%d)\n",i,i);
- >> }
- >>...
-
- Uh, rand() returns a number between 0 and 0x7FFFFFFF inclusive (i.e. a
- positive integer). You limit it with a mod or logical and function:
-
- #define RAND_MAX 1000 /* 0-999 */
-
- main()
- {
- int i;
-
- for (;;) {
- i = rand() % RAND_MAX;
- printf("Random number %d\n", i);
- }
- /* not reached */
- }
-
-
- Note that in many cases people need random numbers that are power of 2
- ranged, i.e. 1, 2, 4, 8 ... etc.. For this you can use a logical AND
- which is *much* faster. For example, (rand() & 1023) returns a
- number between 0 and 1023 inclusive.
-
- -Matt
-
- --
-
- Matthew Dillon dillon@Overload.Berkeley.CA.US
- 891 Regal Rd. uunet.uu.net!overload!dillon
- Berkeley, Ca. 94708 ham: KC6LVW (no mail drop)
- USA
-
-