From owner-freebsd-questions Wed Feb 17 11:31:55 1999 Delivered-To: freebsd-questions@freebsd.org Received: from superior.mooseriver.com (superior.mooseriver.com [208.138.31.113]) by hub.freebsd.org (Postfix) with ESMTP id 25C39115B2 for ; Wed, 17 Feb 1999 11:31:41 -0800 (PST) (envelope-from jgrosch@superior.mooseriver.com) Received: (from jgrosch@localhost) by superior.mooseriver.com (8.8.8/8.8.8) id LAA08171; Wed, 17 Feb 1999 11:31:20 -0800 (PST) (envelope-from jgrosch) Message-ID: <19990217113119.A8120@mooseriver.com> Date: Wed, 17 Feb 1999 11:31:19 -0800 From: Josef Grosch To: cjclark@home.com Cc: patseal@hyperhost.net, freebsd-questions@FreeBSD.ORG Subject: Re: Random Numbers Reply-To: jgrosch@mooseriver.com References: <19990216220931.B5145@mooseriver.com> <199902171508.KAA04420@cc942873-a.ewndsr1.nj.home.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Mailer: Mutt 0.91.1i 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 Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk X-Loop: FreeBSD.ORG 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