Date: Mon, 20 Nov 1995 10:20:36 +0000 () From: Matt Massie <matt@abraxas.wustl.edu> To: Frank Volf <volf@oasis.IAEhv.nl> Cc: freebsd-questions@freebsd.org Subject: Re: What's wrong with this code??? Message-ID: <Pine.BSF.3.91.951120101824.17617T-100000@abraxas.wustl.edu> In-Reply-To: <199511191351.OAA04737@oasis.IAEhv.nl>
next in thread | previous in thread | raw e-mail | index | archive | help
I really do not like srand() or rand(). If you want to really see what
is going on.. make your own pseudo-random number generator like the one
that follows:
/* If you pass it zero, if will seed itself or you can send it time(NULL)*/
float rnd_unit(long int seed)
{
static long int num = 85784;
long int div = 53159, mult = 18327;
float result;
if (seed) num = seed;
num *= mult;
num = num % div;
result = (float)num / div;
return result;
}
---
Matt Massie
matt@abraxas.wustl.edu
On Sun, 19 Nov 1995, Frank Volf wrote:
>
> Hi,
>
> I have an application that uses random() to generate random numbers. For
> generating the random numbers I use the following piece of code:
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <sys/types.h>
> #include <sys/time.h>
> #include <unistd.h>
>
> main()
> {
> int i;
> long t;
>
> t = time(NULL);
> srandom((u_int)t);
> printf("%ld %d %d %d\n",t, random() % 8, random() % 8, random() % 8);
> }
>
> To my surprise the range of numbers generated is not random at all between
> multiple invocations of the program. In fact the random generator seems
> to start again after 16 invocations (with 1 second delay between them
> so t has incremented):
>
> 816788556 6 1 1
> 816788557 5 6 3
> 816788558 5 3 6
> 816788559 4 0 0
> 816788560 4 5 3
> 816788561 3 2 5
> 816788563 2 4 2
> 816788564 2 1 5
> 816788565 1 6 7
> 816788566 1 3 2
> 816788567 0 0 4
> 816788568 0 5 7
> 816788569 7 2 1
> 816788570 7 7 4
> 816788571 6 4 6
>
> 816788572 6 1 1
> 816788573 5 6 3
> 816788574 5 3 6
> 816788575 4 0 0
>
> etc.
>
> What is wrong? Is it a bug in my program (maybe the cast?) or is there a
> problem with the random number generator used in FreeBSD?
>
> Regards,
>
> Frank
>
> ----------------------------------------------------------------------------
> Frank Volf - Internet Access Eindhoven - Digitale Stad Eindhoven
> ----------------------------------------------------------------------------
> || volf@oasis.IAEhv.nl - use for personal mail ||
> || volf@IAEhv.nl - use for Internet Access Eindhoven related mail ||
> || volf@dse.dse.nl - use for Digital City of Eindhoven related mail ||
> ----------------------------------------------------------------------------
> IAE Public Access Unix System - Dial +31.40.2439436 and login as new.
> ----------------------------------------------------------------------------
>
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.BSF.3.91.951120101824.17617T-100000>
