Friday, June 4, 2010

Create Random Numbers

Even if it is maybe unexpected, random parameters do play an important role in the design of many programs. Especially in games random values are highly valued.
But a computer cannot create "real" random numbers, only pseudo-random numbers, since the behaviour of a today's computer is deterministic and has no random elements in it.
Good pseudo-random numbers though look statistically random, meaning every possible number has about the same chance of appearance and the order of appearance is hard to see through. But, in fact they are created by a deterministic algorithm.
Who has become interested in this topic is heartly invited to keep reading somewhere else, here though I just want to list the code.
In C# the class Random is responsible for random numbers. It can either be initialized parameterless or with a seed (that is the number the creation algorithm uses to calculate the first number).
The function Next() finally is the function, which gives us our random number. It has 3 overloadings, which I want to show in the following example:

Random Rnd = new Random(); // initializes the random class
int RndNr1 = Rnd.Next();
int RndNr2 = Rnd.Next(10000);
int RndNr3 = Rnd.Next(0, 2);

The parameterless call saves in RndNr1 a non-negative random number. The random number can be any number of all possible integer - values.
If the function is given a parameter, it is this the exclusive upper bound, so all interger numbers below this bound can appear.
If Next() is called with 2 parameters, the first one is the inclusive lower bound and the second one again the exclusive upper bound. So RndNr3 gets either the value 0 or 1 in the above example.
The created random numbers looked as follows in the example:
RndNr1 = 304286837
RndNr2 = 9060
RndNr3 = 0

No comments:

Post a Comment