Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 16 Feb 1999 22:09:31 -0800
From:      Josef Grosch <jgrosch@mooseriver.com>
To:        Patrick Seal <patseal@hyperhost.net>, freebsd-questions@FreeBSD.ORG
Subject:   Re: Random Numbers
Message-ID:  <19990216220931.B5145@mooseriver.com>
In-Reply-To: <Pine.BSF.4.05.9902162134210.809-100000@foobar.hyperhost.net>; from Patrick Seal on Tue, Feb 16, 1999 at 09:36:40PM -0500
References:  <Pine.BSF.4.05.9902162134210.809-100000@foobar.hyperhost.net>

next in thread | previous in thread | raw e-mail | index | archive | help
On Tue, Feb 16, 1999 at 09:36:40PM -0500, Patrick Seal wrote:
> In this the best way to get a number from one to ten in C:
> 
> #include <stdlib.h>
> 
> randn(float value) {
>     value = random() * value / 2147483648.0;
>     return(value);
> }
> 
> n = randn(10.0) + 1
> 
> printf("%i", n);
> 
> I realize it's platform dependent.  Is there a better way?

You should seed the random number generator first. Try the following;

int randn()
{
    int  rc = 0;

    pid_t   pid = getpid();
    time_t  now = 0;

    long value = 0L;
    unsigned long seed = 0L;

    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 OK for a quick hack. Play around with it. You should also consult
the man pages for random


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?19990216220931.B5145>