Register forum user name Search FAQ

Gammon Forum

Notice: Any messages purporting to come from this site telling you that your password has expired, or that you need to verify your details, confirm your email, resolve issues, making threats, or asking for money, are spam. We do not email users with any such messages. If you have lost your password you can obtain a new one by using the password reset link.

Due to spam on this forum, all posts now need moderator approval.

 Entire forum ➜ Electronics ➜ Microprocessors ➜ Lightweight pseudo-random number generator for Arduino

Lightweight pseudo-random number generator for Arduino

Postings by administrators only.

Refresh page


Posted by Nick Gammon   Australia  (23,158 posts)  Bio   Forum Administrator
Date Thu 02 Oct 2014 05:21 AM (UTC)

Amended on Thu 02 Oct 2014 05:42 AM (UTC) by Nick Gammon

Message
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).

- Nick Gammon

www.gammon.com.au, www.mushclient.com
Top

The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).

To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.


8,035 views.

Postings by administrators only.

Refresh page

Go to topic:           Search the forum


[Go to top] top

Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.