avr-gcc-list
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [avr-gcc-list] rand()


From: Matthias Granberry
Subject: Re: [avr-gcc-list] rand()
Date: Wed, 10 Jul 2002 21:23:23 -0500 (CDT)

I just took a look at it and decided to see what would happen when you do
use rand()%4.  Using the seed given in the test 'main', rand()%4 gives the
repeating sequence 0,1,2,3,0,..., so I would recommend being very careful
how you get these numbers.  You might want to do a right-shift several
places and then perform a modulus or some similar operation to get good
"random" numbers.

Matthias Granberry


On Wed, 10 Jul 2002, Matthias Granberry wrote:

> In-Reply-To: <address@hidden> (Torsten Hahn's message
> of "Wed, 10 Jul 2002 10:20:05 +0200")
> References: <address@hidden>
> 
> Last time I checked, it was there.  The AVR micros have the timers and
> some even have an input capture.  You could seed it by detecting a
> level change on an external RC oscillator or some similar scheme.  It
> looks like it returns an unsigned 32-bit int using a linear
> congruential scheme, so it might have some period problems, but it
> might not be too bad.  One thing that you might want to look into is
> the randomness of the low-order bits.
> 
> Here is the actual calculation:
> 
> static int
> do_rand(unsigned long *ctx)
> {
>       return ((*ctx = *ctx * 1103515245 + 12345) % ((unsigned long
> int)RAND_MAX + 1));
> }
> 
> 
> I haven't done any calculations or tests on it, but it is possible
> that if you try and get a random number by calling (n=rand()%10;) or
> something similar, the numbers will quickly fall into a loop, giving
> you fairly poor "random" numbers.
> 
> Matthias Granberry
> University of Texas at Dallas
> 
> Torsten Hahn <address@hidden> writes:
> 
> > Hi,
> >
> > Has somebody still implemented an random number generator on the avr
> ? May be, 
> > it would be nice such a function in the avr-libc. Random number routines
> are 
> > not the problem i think but how to generate a "seed". On a pc you can
> use the 
> > time() function. Has somebody an idea how to do it on avr ?
> >
> > Cu,
> > Torsten.
> > -- 
> > Torsten Hahn 
> > TU Bergakademie Freiberg - Institut fr Experimentelle Physik 
> > Silbermannstrae 1, 09596 Freiberg
> > mail: address@hidden
> > phone: +49 3731 392670 
> > avr-gcc-list at http://avr1.org
> 
> 
> 

avr-gcc-list at http://avr1.org



reply via email to

[Prev in Thread] Current Thread [Next in Thread]