Arithmetic Operations

Random numbers are useful in many situations, not just games, but also in serious applications such as simulations, educational software and others.

The statement R= Rnd() assigns a value to R such that 0 <= R<1.

The table below shows the transformation of a random number to a random value from 1 to 6:

R = Rnd() R = R * 6 R = (Int)R R = R + 1;
0.000 0.000 0 1
0.399 2.394 2 3
0.575 3.450 3 4
0.776 4.656 4 5
0.999 5.994 5 6
0 <= n < 1 0.0 <= n < 6.0 0 <= R< 6 1 <= R<= 6

Instead of doing this step-by-step as shown above the following statement can be used:
R=Rnd() * 6 + 1

A general rule is to multiply by the number of values in the range and then add the lowest value in the range.
The Flash movie below allows you to enter the first and last values and see the Visual Basic statement to compute the random numbers.
Type the first and last values in the range, then press enter to generate random numbers in the specified range.

Get Adobe Flash player

Random Points on the Form

To get a random point on the form use the following statements:
X = Rnd() * Me.Width
Y = Rnd() * Me.Height

Weighted Values

In the examples above, each value in the range has an equal chance of being selected. This would be true if we were using random numbers to roll dice, or flip a coin. In other application, we prefer to have one value appear more often than other values. In a bank simulation, we may say that 80% of the customers have just one transaction, 15% have 2 transactions, and 5% have 3 transactions. The easiest way to handle problems of this type is to generate a random value from 1 to 100 and then assign a range of value based on the percentage:

1..80 = 1 transaction
81..95 = 2 transactions
96..100 = 3 transactions

We will use random values in the drawing lesson to generate random colors.

NEXT: Boolean Expressions in Visual Basic