Skip to content

Commit bd03e26

Browse files
pbrierrobertinant
authored andcommitted
Added internal srandom() and random() function, fixes Issue energia#63
1 parent 97a90b7 commit bd03e26

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

hardware/msp430/cores/msp430/WMath.cpp

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,30 @@
2626
extern "C" {
2727
#include "stdlib.h"
2828
}
29-
#if 0
29+
30+
31+
/*
32+
* Internal srandom() and random() implmentation,
33+
* a simple pseudo-random number generator is the Multiply-with-carry method invented by George Marsaglia.
34+
* It is computationally fast and has good (albeit not cryptographically strong)
35+
* From: http://en.wikipedia.org/wiki/Random_number_generation#Computational_methods
36+
*/
37+
static long m_w =123; /* must not be zero */
38+
static long m_z =98765432; /* must not be zero */
39+
40+
static void srandom(long n)
41+
{
42+
m_w = 123 ^ n;
43+
m_z = 98765432 ^ n-1;
44+
}
45+
46+
static unsigned long random()
47+
{
48+
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
49+
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
50+
return (m_z << 16) + m_w; /* 32-bit result */
51+
}
52+
3053
void randomSeed(unsigned int seed)
3154
{
3255
if (seed != 0) {
@@ -50,7 +73,7 @@ long random(long howsmall, long howbig)
5073
long diff = howbig - howsmall;
5174
return random(diff) + howsmall;
5275
}
53-
#endif
76+
5477

5578
long map(long x, long in_min, long in_max, long out_min, long out_max)
5679
{

0 commit comments

Comments
 (0)