From owner-freebsd-questions Wed Feb 17 7: 7:17 1999 Delivered-To: freebsd-questions@freebsd.org Received: from cc942873-a.ewndsr1.nj.home.com (cc942873-a.ewndsr1.nj.home.com [24.2.89.207]) by hub.freebsd.org (Postfix) with ESMTP id 4F07511029 for ; Wed, 17 Feb 1999 07:07:11 -0800 (PST) (envelope-from cjc@cc942873-a.ewndsr1.nj.home.com) Received: (from cjc@localhost) by cc942873-a.ewndsr1.nj.home.com (8.8.8/8.8.8) id KAA04420; Wed, 17 Feb 1999 10:08:41 -0500 (EST) (envelope-from cjc) From: "Crist J. Clark" Message-Id: <199902171508.KAA04420@cc942873-a.ewndsr1.nj.home.com> Subject: Re: Random Numbers In-Reply-To: <19990216220931.B5145@mooseriver.com> from Josef Grosch at "Feb 16, 99 10:09:31 pm" To: jgrosch@mooseriver.com Date: Wed, 17 Feb 1999 10:08:41 -0500 (EST) Cc: patseal@hyperhost.net, freebsd-questions@FreeBSD.ORG Reply-To: cjclark@home.com X-Mailer: ELM [version 2.4ME+ PL40 (25)] MIME-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk X-Loop: FreeBSD.ORG 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; 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); > } 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). -- Crist J. Clark cjclark@home.com To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message