Zebra0.com

numbersRandom Numbers in VB 6

Random Numbers in VB 6

Random Numbers

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 script below allows you to enter the first and last values and see the VB.Net statement to compute the random numbers.

Put in the first and last values

first last

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

Exercise: (not a lab assignment) Create a program with one button. When the button is clicked generate random x and y values then draw a square at that point. Test. Modify so that 80% of the boxes are blue, 15% red, and 5% yellow.