Can anyone tell me what sort of algorithm the arduino uses to create the numbers in the random() function?
Thanks
Can anyone tell me what sort of algorithm the arduino uses to create the numbers in the random() function?
Thanks
ATTRIBUTE_CLIB_SECTION
static long
do_random(unsigned long *ctx)
{
/*
* Compute x = (7^5 * x) mod (2^31 - 1)
* wihout overflowing 31 bits:
* (2^31 - 1) = 127773 * (7^5) + 2836
* From "Random number generators: good ones are hard to find",
* Park and Miller, Communications of the ACM, vol. 31, no. 10,
* October 1988, p. 1195.
*/
long hi, lo, x;
x = *ctx;
/* Can't be initialized with 0, so use another value. */
if (x == 0)
x = 123459876L;
hi = x / 127773L;
lo = x % 127773L;
x = 16807L * lo - 2836L * hi;
if (x < 0)
x += 0x7fffffffL;
return ((*ctx = x) % ((unsigned long)RANDOM_MAX + 1));
}
static unsigned long next = 1;
ATTRIBUTE_CLIB_SECTION
long
random(void)
{
return do_random(&next);
}
This could be a bit offtopic, but I found this site about randomness, the provided example seems to improve the overall random generator inside arduino; at setup() write:
unsigned long seed=0, count=32;
while (--count)
seed = (seed<<1) | (analogRead(0)&1);
randomSeed(seed);
Note: this is only effective if A0 is not used by anything else.
We've tried the "read analog input" trick before. It works fairly well but is certainly not random. There is a mega thread about this on the forum somewhere, complete with scatter graphs.
Rob
I said "seems to improve"..
Also pay attention that using the previous block of code is far better than using "randomSeed( analogRead(0) );".
@fuh
your code indeed generates a better seed than just one analogRead(); wrote about it some time ago and used the internal temp sensor (not supported by all duinos)
Same problems, but it keeps your A0 line available