Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 17 Feb 1999 10:08:41 -0500 (EST)
From:      "Crist J. Clark" <cjc@cc942873-a.ewndsr1.nj.home.com>
To:        jgrosch@mooseriver.com
Cc:        patseal@hyperhost.net, freebsd-questions@FreeBSD.ORG
Subject:   Re: Random Numbers
Message-ID:  <199902171508.KAA04420@cc942873-a.ewndsr1.nj.home.com>
In-Reply-To: <19990216220931.B5145@mooseriver.com> from Josef Grosch at "Feb 16, 99 10:09:31 pm"

next in thread | previous in thread | raw e-mail | index | archive | help
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




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199902171508.KAA04420>