Lightweight pseudo-random number generator for Arduino

Posted by Nick Gammon on Thu 02 Oct 2014 05:21 AM — 1 posts, 9,494 views.

Australia Forum Administrator #0
This PRNG is supposed to improve upon the built-in rand() function which comes with the Arduino standard library, and is also faster.


/* Implementation of a 32-bit KISS generator which uses no multiply instructions */

// Initial seed
static unsigned long x = 123456789,
                     y = 234567891,
                     z = 345678912,
                     w = 456789123,
                     c = 0;

unsigned long JKISS32 ()
  {
  long t;
  y ^= y << 5; 
  y ^= y >> 7; 
  y ^= y << 22;
  t = z + w + c; 
  z = w; 
  c = t < 0; 
  w = t & 2147483647;
  x += 1411392427;
  return x + y + w;
  }  // end of JKISS32


Author of the generator: George Marsaglia

Wikipedia article on George Marsaglia.

Example seeder:


void Seed_JKISS32 (const unsigned long newseed)
  {
  if (newseed != 0)
    {
    x = 123456789;
    y = newseed;
    z = 345678912;
    w = 456789123;
    c = 0;
    }
  }  // end of Seed_JKISS32


Of course, a better seeder would change the other numbers as well. Avoid seeding with y = 0.

For more info see this PDF: http://www.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf

If you are using this on a "proper" PC (rather than an Arduino) replace "long" by "int" (assuming your int is 32-bits).