Coding is highly addictive. I suspect it has to do with the combination of the brain being the bottleneck, like all good puzzles; rapid iteration allowing you to see a result slowly emerge, and the fact that once you get done, you'll have something tangable as a reward that will serve you for a long time.
It's somewhat like combining crossword puzzles, woodworking, and sketching.
Showing posts with label Random. Show all posts
Showing posts with label Random. Show all posts
Monday, April 8, 2013
Tuesday, February 12, 2013
HOWTO Make a Quick and Dirty (Pseudo)Random Number Generator
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
a, m ,c's. 1Implementation
#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.- These conditions require some discrete mathematics that are too long to go in to here; it involves coprime numbers and recurrence relations. (Please point out if I've missed some simple explaination in the comments, I'm fairly new to this!)↩
Subscribe to:
Posts (Atom)