Visual Basic Explorer
Visual Basic Explorer
 Navigation
 Home


 Coding
 Source Code

 FAQ Center

 VB Tips

 Downloads

 ToolBox

 Tutorials

 VB Games

 VB News

 VB Award

 VB Forums



 Affiliates
 Planet Source Code

 Rent a Coder

 DirectX4VB


 Misc
 Search

 Feedback

 Advertise

 About


Need to hire
a VB coder?

Please support our sponsor:

 Home 
 Site Map 
 Forums 
 News 
 Feedback 

Random Numbers

By Brian P. Duckworth

Lesson #1 - The Basics of Random Numbers

Sometimes it's useful to have the program pick a value "at random". That is to say, have the program generate a value that can't be predicted. In the case of card games, the program might choose any of the 52 playing cards in a standard deck. Or, perhaps, randomly select one of the six sides of a standard die. In the case of video games, a computer-controlled character might have to select a direction in which to move. All of these situations can easily be handled through the use of random numbers.

How Do I Get Random Numbers?

The Visual Basic function Rnd is used to return psuedo-random values.

Each time the Rnd function is used, a new psuedo-random value is returned. The values returned are always less than one (1), but greater than or equal to zero (0). That is to say, VB generates random numbers which may be as low as zero (0), but will never reach the value of one (1).
    0 <= Rnd < 1

Values in that range may not seem very useful, but there's a simple formula for converting the values returned by Rnd into a more useful range:
    Int((HighestValue - LowestValue + 1) * Rnd) + LowestValue
Creating a function that encapsulates this formula will help simplify the generation of psuedo-random values.
    '===============================================
    'Rand - Return a random number in a given range.
    '
    'Parameters:
    '  Low  - The lower bounds of the range.
    '  High - The upper bounds of the range.
    '
    'Returns:
    '  Returns a random number from Low..High.
    '===============================================
    
    Public Function Rand(ByVal Low As Long, _
                         ByVal High As Long) As Long
      Rand = Int((High - Low + 1) * Rnd) + Low
    End Function
    
With this function, random values can easily be generated to simulate such things as dealing cards or rolling dice.
    DieValue = Rand(1, 6)
    CardValue = Rand(1, 52)
    

Initializing the Random Numbers

Each time a program is run, the psuedo-random values returned by Rnd are always the same! Obviously, this is very predictable and not random at all. However, VB has also provided the Randomize method.

Use Randomize to initialize VB's random number generator. This is called seeding. To avoid generating the same sequence of psuedo-random values, call Randomize before you call Rnd; but this only has to be done once. A good place to seed the psuedo-random number generator is in the Form's Load event:
    Private Sub Form_Load()
      'Initialize the random # generator.
      Randomize
    End Sub
    

Repeating Random Numbers

If Randomize is not called before Rnd, the same series of psuedo-random values will be returned. It's as if VB always starts returning values from the first entry of that conceptual internal list of 1 million psuedo-random values.

There are occasions when it will be desireable to repeat a series of psuedo-random values, but not always from the "first" entry of the internal list of 1 million. To start somewhere else in that conceptual list, call Rnd with a negative parameter, followed by a call to Randomize, passing it the starting point. For example:
    'Tell VB to initialize using Randomize's parameter.
    Rnd -1
    'Tell VB to use 123 as the initialization point (seed).
    Randomize 123
    
By replacing 123 with a different seed value, the starting point into the conceptual list of 1 million psuedo-random values changes, but each time the program is run, the values returned will always be in the same sequence.

Why Would I Want Repeating Random Numbers?

There are at least two good senarios where repeatable sequences of psuedo-random numbers can be beneficial.

First, it's good for testing. Testing programs that use random values is made easier if the sequence of random values is foreknown. If a program makes decisions based on random values and it is know what those values will be, it is easier to predict what decisions the program should make.

Second, certain types of encryption algorythms utilize repeatable random number sequences. By properly seeding the psuedo-random number generator, a repeatable pattern can be generated. Since there are many possible seed values to Randomize, it would be difficult for anyone to guess which one has been chosen. Lesson #3 covers one possible usage of random numbers in an encryption scheme.

What Was That Last Random Number?

Passing zero as the parameter to Rnd will cause Rnd to return the same psuedo-random value that it did in the previous call. For example:
    Dim r1 As Single
    Dim r2 As Single
    
    Randomize
    
    'Generate a random number.
    r1 = Rnd
    'Generate the same random number as last time.
    r2 = Rnd(0)
    
    'r1 should equal r2
    If r1 = r2 Then
      MsgBox "That's what's suppose to happen."
    Else
      MsgBox "It didn't work the way Brian said it would."
    End If
    

Why Would I Want The Last Random Number?

I have no idea. :-)

Lesson Project

There is an associated project that demonstrates the material covered in this lesson. Download it HERE.

Placing the mouse over a control will display a ToolTip that describes the control's function:

What's Next?

Lesson #2 will discuss some of the ways random numbers can be used.

© 2000, Visual Basic Explorer

Lesson 1 Lesson 2 Lesson 3 Download All (All 3 lessons w/samples)





Home | About | What's New | Source Code | FAQ | Tips & Tricks | Downloads | ToolBox | Tutorials | Game Programming | VB Award | Search | VB Forums | Feedback | VBNews | Copyright & Disclaimer | Advertise | Privacy Policy |

Quick searches: Site Search | Advanced Site Search 

Copyright 2002 by Exhedra Solutions, Inc.
By using this site you agree to its terms and conditions
VB Explorer and VBExplorer.com are trademarks of Exhedra Solutions, Inc.