If you ever need to build your own quick and dirty (pseudo-)random number generator it actually isn't that hard. This generator is used in various real-world systems:
- Visual Basic (to version 6)
- A few ANSI C implementations, including
glibc
- Java's Random library
The implementation will iterate over all numbers [0,m) when using proper
a
,
m
,
c
's.
Implementation
#include <stdio.h>
#include <unistd.h>
const long m = 4294967296; // 2 ^ 32
const long a = 1103515245;
const long c = 12345;
long lastX = 0;
long nrandom() {
lastX = (a * lastX + c) % m;
return lastX;
}
void seed(int num)
{
lastX = num;
}
int main()
{
int i;
seed(getpid());
for(i = 0; i < 1000; i++)
printf("%li\n", nrandom());
}
Note that this implementation only generates m pseudorandom numbers, in this case 4,294,967,296; so if you need more, you'll want to use a
different algorithm.
No comments:
Post a Comment