CST2601 Visual Basic I
Notes on Rnd and Randomize


Rnd Function

Returns a Single containing a random number.

Syntax

Rnd[(number)]

The optional number argument is a Single or any valid numeric expression.

Return Values

If number is Rnd generates
Less than zero The same number every time, using number as the seed.
Greater than zero The next random number in the sequence.
Equal to zero The most recently generated number.
Not supplied The next random number in the sequence.
 

Remarks

The Rnd function returns a value less than 1 but greater than or equal to zero.

The value of number determines how Rnd generates a random number:

For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.

Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

Note   To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

Rnd Function Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

Dim MyValue
MyValue = Int((6 * Rnd) + 1)   ' Generate random value between 1 and 6.

Randomize Statement

Initializes the random-number generator.

Syntax

Randomize [number]

The optional number argument is a Variant or any valid numeric expression.

Remarks

Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.

If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.

Note   To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

Randomize Statement Example

This example uses the Randomize statement to initialize the random-number generator. Because the number argument has been omitted, Randomize uses the return value from the Timer function as the new seed value.

Dim MyValue
Randomize   ' Initialize random-number generator.

MyValue = Int((6 * Rnd) + 1)   ' Generate random value between 1 and 6.

seed

An initial value used to generate pseudorandom numbers. For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.