home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.programming
- Path: sparky!uunet!newsgate.watson.ibm.com!yktnews!admin!curt
- From: curt@watson.ibm.com (Curt McDowell)
- Subject: Re: Any simple Random Number generators?
- Sender: news@watson.ibm.com (NNTP News Poster)
- Message-ID: <1992Aug20.143244.6305@watson.ibm.com>
- Date: Thu, 20 Aug 1992 14:32:44 GMT
- Lines: 61
- Disclaimer: This posting represents the poster's views, not necessarily those of IBM
- References: <13AUG199218224504@judy.uh.edu> <1992Aug14.104121.29374@corax.udac.uu.se> <3283@creatures.cs.vt.edu> <1992Aug18.143439@fdr.jsc.nasa.gov>
- Nntp-Posting-Host: gorby.watson.ibm.com
- Organization: IBM T.J. Watson Research Center
- Keywords: random, shift
-
- In article <1992Aug18.143439@fdr.jsc.nasa.gov>, shirley@fdr.jsc.nasa.gov (Bill Shirley [CSC]) writes:
- >
- > If you just want it to reseed differently
- >
- > random(time())
- >
- > will do it
- > --
- > Bill Shirley | ``Computer Science is not about computers any
- > shirley@fdr.jsc.nasa.gov| more than astronomy is about telescopes.''
-
- No, that won't quite do it. Firstly, the call is srandom. Secondly,
- time() requires an argument or it will core dump. What you wanted to
- say was srandom(time(0)).
-
- A slightly better way is srandom(time(0) + getpid()), since if your
- program runs quick it might be run more than once a second (e.g. from a
- shell script).
-
- Here are my favorite convenience #defines when my program is not in
- a hurry:
-
- #define rander() (((unsigned long) random() << 5) ^ \
- (unsigned long) random() ^ \
- ((unsigned long) random() >> 5))
-
- #define srnd() srandom(time(0) + getpid())
- #define rnd(n) (rander() % (n))
-
- Here is my favorite way to generate vaguely random numbers when my
- program is in a tremendous hurry (e.g. as for test data). It's a
- pseudo-random shift register of the type detailed in a previous note
- from Andy Collins, cycling through every possible bit combination
- except 0 before recycling. The numbers are far from ideally random,
- but it's very fast. You may be able to find a way to make them
- appear more random.
-
- /*
- * randomize_buffer
- *
- * Fill a buffer of 'len' unsigned longs with semi-random data.
- */
-
- void randomize_buffer(buf, len)
- unsigned long *buf;
- int len;
- {
- unsigned long b;
-
- while ((b = rander()) == 0)
- ;
-
- while (len--) {
- *buf++ = b;
- b = b << 1 | (b >> 30 ^ b >> 27) & 1;
- }
- }
-
- --
- Curt McDowell
- IBM T. J. Watson Research Center
-