Re: Random Number Generator Matchup Arduino / Python

Certainly. Just use the same algorithm. The default one on the Arduino is the Park-Miller "Minimal Standard".

If you need an implementation of that one or another one, let me know. I can either provide one or guide you to one.

Searching for the constants is a good way to pin down the default Arduino generator...

It is one of these. You can check the Arduino code for which one is used. They should be functionally identical. Scroll towards the bottom for the actual code.

http://svn.savannah.nongnu.org/viewvc/trunk/avr-libc/libc/stdlib/rand.c?revision=1944&root=avr-libc&view=markup

http://svn.savannah.nongnu.org/viewvc/trunk/avr-libc/libc/stdlib/random.c?revision=1944&root=avr-libc&view=markup

This is a very fast one, the two initializers are the "seed"

// An example of a simple pseudo-random number generator is the 
// Multiply-with-carry method invented by George Marsaglia.
// two initializers (not null)
unsigned long m_w = 1;
unsigned long m_z = 2; 

unsigned long getRandom()
{
    m_z = 36969L * (m_z & 65535L) + (m_z >> 16);
    m_w = 18000L * (m_w & 65535L) + (m_w >> 16);
    return (m_z << 16) + m_w;  /* 32-bit result */
}

python version is like this

m_w = 1
m_z = 2
	
def getRandom():
    global m_w
    global m_z
    m_z = (36969L * (m_z & 65535L) + (m_z >> 16)) & 0xFFFFFFFF
    m_w = (18000L * (m_w & 65535L) + (m_w >> 16)) & 0xFFFFFFFF
    return ((m_z << 16) + m_w) & 0xFFFFFFFF

for i in range(10):
    print getRandom()

there might be a need to keep datatypes 32 bit (extra masking)

[yes -> added]

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.