views:

607

answers:

5

How do random number generator works? (for example in C/C++ Java)

How can I write my own random number generator? (for example in C/C++ Java)

+2  A: 

I found this one for Java:

http://www.javamex.com/tutorials/random_numbers/java_util_random_algorithm.shtml

by googling how random functions work java

I'm sure the answer is language-specific, but you can try altering my Google query for the language of your choice.

David Stratton
+9  A: 

Maybe you can start here: http://en.wikipedia.org/wiki/Random_number_generation

Konamiman
+1. Good link. I like Wikipedia, and this answer is pretty detailed.
David Stratton
+1. The section on "Computational methods" starts by describing a linear congruential generator, which is the basic algorithm usually implemented in courses, and the basis for most "real" sytems as well.
Rasmus Kaj
+1 - I was going to answer with http://xkcd.com/221/ as that's the kind of mood I'm in today :)
George Shore
+1  A: 
littlegreen
A millisecond timer is not a fast changing system, for most computational purposes it is a semi-fixed number, changing once in a while. And when it does change, it changes in a completely predictable terms. In best case the time should be used as a seed, and only once in a while to make sure that the time has changed completely before using it again. So better than a timer is a system that changes *really* rapidly, and non predictive.
daramarak
+4  A: 

One of the things to keep in mind is that there are no 'true' random number generators. They just generate numbers that look random to us mere mortals.

One of the easiest examples of this (to implement, as well) is the Linear congruential generator. Sure, the numbers look unpredictable to you and me, but they're actually evenly spaced within a finite field.

Of course, some generators, like Blum Blum Shub aren't predictable for an outsider even if he applies serious mathematical skills and computing power to the task, but at the fundamental level, random number generators aren't random; they're regular and predictable.

Michiel Buddingh'
\dev\random is more random, and you can also attach something to measure things like exact air temp or a geiger counter for more randomness.
James Black
+1  A: 

There is a lot of information available about how they are working ... see Konamiman's answer and use google a bit.

Why would you like to write a new random generator? You probably should not try to do so ... until you need something very special. For example in a game you could use a shuffle bag which produces 'fair' random values - have a look at this interesting question on SO.
I post this here, because I really liked the idea and implementation when I read about it the first time :)

tanascius