home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / c / 11800 < prev    next >
Encoding:
Text File  |  1992-07-30  |  1.8 KB  |  68 lines

  1. Xref: sparky comp.lang.c:11800 comp.sys.amiga.programmer:11845
  2. Path: sparky!uunet!overload!dillon
  3. From: dillon@overload.Berkeley.CA.US (Matthew Dillon)
  4. Newsgroups: comp.lang.c,comp.sys.amiga.programmer
  5. Subject: Re:  Matt Dillon's DICE (Amiga C) and rand() function
  6. Distribution: world
  7. Message-ID: <dillon.0kbn@overload.Berkeley.CA.US>
  8. References:  <1992Jul29.081247.1@gallua> <1992Jul29.163704.26489@proxxi.se>
  9. Date: 30 Jul 92 22:57:34 PST
  10. Organization: Not an Organization
  11. Lines: 55
  12.  
  13. In article <1992Jul29.163704.26489@proxxi.se> elias@proxxi.se (Elias M}rtensson (proxxi)) writes:
  14. >CADS_COLE@GALLUA.BITNET (Kevin Cole; Washington DC) writes:
  15. >
  16. >>Date Sent:  29-Jul-1992  08:09:36
  17. >
  18. >>Greetings from the void,
  19. >
  20. >>Here's a very short C program that doesn't do what the documentation claims.
  21. >>According to Matt Dillon's DICE documents, I can limit the range of values
  22. >>Thanx.
  23. >
  24. >>     #include <stdio.h>
  25. >>     #include <stdlib.h>
  26. >>     #define RAND_MAX ((1023))
  27. >>     main()
  28. >>     {
  29. >>    int i;
  30. >>    for (;;)
  31. >>    {
  32. >>     i = rand();
  33. >>     printf("Random number %04X (%d)\n",i,i);
  34. >>    }
  35. >>...
  36.  
  37.     Uh, rand() returns a number between 0 and 0x7FFFFFFF inclusive (i.e. a
  38.     positive integer).    You limit it with a mod or logical and function:
  39.  
  40.     #define RAND_MAX    1000       /*    0-999    */
  41.  
  42.     main()
  43.     {
  44.     int i;
  45.  
  46.     for (;;) {
  47.         i = rand() % RAND_MAX;
  48.         printf("Random number %d\n", i);
  49.     }
  50.     /* not reached */
  51.     }
  52.  
  53.  
  54.     Note that in many cases people need random numbers that are power of 2
  55.     ranged, i.e. 1, 2, 4, 8 ... etc..  For this you can use a logical AND
  56.     which is *much* faster.  For example,   (rand() & 1023) returns a
  57.     number between 0 and 1023 inclusive.
  58.  
  59.                         -Matt
  60.  
  61. --
  62.  
  63.     Matthew Dillon        dillon@Overload.Berkeley.CA.US
  64.     891 Regal Rd.        uunet.uu.net!overload!dillon
  65.     Berkeley, Ca. 94708     ham: KC6LVW (no mail drop)
  66.     USA
  67.  
  68.