I want to generate random numbers manually. I know that every language have the rand or random function, but I'm curious to know how this is working. Does anyone have code for that?
http://en.wikipedia.org/wiki/Random_number_generator
Describes the different types of random number generators and how they are created.
Have a look at the following:
Linear Congruential Generator - a popular approach also used in Java
List of Random Number Generators
And here's another link which elaborates on the use of LCG in Java's Random class
I assume you mean pseudo-random numbers. The simplest one I know (from writing videogames games back on old machines) worked like this:
seed=seed*5+1;
You do that every time random is called and then you use however many low bits you want. *5+1 has the nice property (IIRC) of hitting every possibility before repeating, no matter how many bits you are looking at.
The downside, of course, is its predictability. But that didn't matter in the games. We were grabbing random numbers like crazy for all sorts of things, and you'd never know what number was coming next.
Do a couple things like this in parallel, and combine the results. This is a linear congruential generator.
I want to generate random numbers manually.
I would roll some dice ... (SCNR)
More seriously, I roll a pair of dice for creating passwords.
POSIX.1-2001 gives the following example of an implementation of rand()
and srand()
, possibly useful when one needs the same sequence on two different machines.
static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int myrand(void) {
next = next * 1103515245 + 12345;
return((unsigned)(next/65536) % 32768);
}
void mysrand(unsigned seed) {
next = seed;
}