Random numbers
By: Lorenzo Dalla Vecchia Date: 16/07/2001

Visual Basic, like many other programming languages, can generate and pick random numbers. The main function involved in the process is Rnd: each time Rnd is called, it will return a number in the range 0.000-0.999.

result = Rnd

An important thing that each programmer must keep in mind, is that a computer is not able of generating real random numbers. A machine made up of circuits, chips, wires and transistors can't generate anything at random. The process of generating random numbers involves the iteration of a mathematical function. Basically, an equation is at first fed with a number, called the seed, and then fed a second time with the first result, a third time with the second result and so on.

Since, unless differently specified, VB always uses the same seed, Rnd will always return the same sequence of numbers. For this reasons the numbers generated by computers are sometimes called pseudo-random or pseudo-casual numbers.
It is then important to "shuffle" the sequence each time you want to use
Rnd using a different seed each time. This is done with the Randomize instruction, whose syntax is:

Randomize [seed]

Commonly, programmers use to feed Randomize with the value of the Timer function (i.e. Randomize Timer), representing the number of seconds elapsed from midnight, that is most likely to change each time the program is run. Another way of using Timer as seed is omitting the parameter (i.e. Randomize).
So, remember to put a
Randomize instruction at the beginning of your code, maybe in the Form_Load procedure.

The last thing to know is how to turn the sequence of decimal numbers (i.e. 0.267, 0.547, 0.946) into integer numbers (i.e. 4, 45, 21), more useful in programming.
The suggested syntax is the following:

result = Int((top - bottom + 1) * Rnd + bottom)

Replace top and bottom with the upper and lower limits of the sequence you want generated; then, pick the numbers in sequence using Rnd.
The following example picks 3 pseudo-random integers in the range 60-100.

Dim RndNum As Integer
Dim i As Integer

'Shuffles the sequence
'Randomize Timer would have been the same

Randomize

'Picks 3 random numbers
For i = 1 To 3

    RndNum = Int((100 - 60 + 1) * Rnd + 60)
    MsgBox RndNum
Next i

See how Randomize is used once at the beginning of the code and not before each Rnd call.

Click Here!


Visual Basic Programming Zone is a website by Lorenzo Dalla Vecchia.
To contact the Webmaster, click here.
Hosted by InWind: www.inwind.it