Date: Wed, 17 Feb 1999 11:31:19 -0800 From: Josef Grosch <jgrosch@mooseriver.com> To: cjclark@home.com Cc: patseal@hyperhost.net, freebsd-questions@FreeBSD.ORG Subject: Re: Random Numbers Message-ID: <19990217113119.A8120@mooseriver.com> In-Reply-To: <199902171508.KAA04420@cc942873-a.ewndsr1.nj.home.com>; from Crist J. Clark on Wed, Feb 17, 1999 at 10:08:41AM -0500 References: <19990216220931.B5145@mooseriver.com> <199902171508.KAA04420@cc942873-a.ewndsr1.nj.home.com>
next in thread | previous in thread | raw e-mail | index | archive | help
On Wed, Feb 17, 1999 at 10:08:41AM -0500, Crist J. Clark wrote: > Josef Grosch wrote, > > On Tue, Feb 16, 1999 at 09:36:40PM -0500, Patrick Seal wrote: > > You should seed the random number generator first. Try the following; Yes, you are correct. > > And it is my understanding you are best off only seeding it once. My > minor changes to the code are not led by a '>.' > > > int randn() > > { > > int rc = 0; > > long value = 0L; > static unsigned long seed = 0L; > > > if ( ! seed ) { > > pid_t pid = getpid(); > > time_t now = 0; > > > > > > struct timeval tp; > > struct timezone tzp; > > > > gettimeofday(&tp, &tzp); > > now = tp.tv_sec; /* unnecessary but nice during debugging */ > > seed = (unsigned long)(now / pid); > > srandom(seed); > } > > > value = random(); > > > > rc = (value % 10); > > > > return (rc); > > } This is much better than my ugly little hack. > > There is a _tiny_ chance the seed might be exactly '0' after the > first pass, in which case the seed will be recalculated next > use. However, this reduces to the previous algorithm which redid the > seed each time. > > Also, if you want to make the code work like the original poster, > where the range of the random number is specified, change the > declaration of the function to take an arg, > > int randn(int range) > > And then instead of the last three lines, > > return (random() % range); > > The return value is 0 to (range - 1). The above hack was ment more of a demo of what needs to be done. There are a number of places in the code that could be improved. Thanks Josef -- Josef Grosch | Another day closer to a | FreeBSD 3.0 jgrosch@MooseRiver.com | Micro$oft free world | UNIX for the masses To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?19990217113119.A8120>