[Home] [Downloads] [Search] [Help/forum]

Register forum user name Search FAQ

Gammon Forum

[Folder]  Entire forum
-> [Folder]  Electronics
. -> [Folder]  Microprocessors
. . -> [Subject]  Lightweight pseudo-random number generator for Arduino

Lightweight pseudo-random number generator for Arduino

Postings by administrators only.

[Refresh] Refresh page

Posted by Nick Gammon   Australia  (22,966 posts)  [Biography] 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

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
[Go to top] 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.


Postings by administrators only.

[Refresh] Refresh page

Go to topic:           Search the forum

[Go to top] top

Quick links: MUSHclient. MUSHclient help. Forum shortcuts. Posting templates. Lua modules. Lua documentation.

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


Written by Nick Gammon - 5K   profile for Nick Gammon on Stack Exchange, a network of free, community-driven Q&A sites   Marriage equality

Comments to: Gammon Software support
[RH click to get RSS URL] Forum RSS feed ( https://gammon.com.au/rss/forum.xml )

[Best viewed with any browser - 2K]    [Hosted at HostDash]