RANDOM

BS1 icon BS2 icon BS2e icon BS2sx icon BS2p icon BS2pe icon BS2px icon

RANDOM Examples

 

 

 

Syntax: RANDOM Variable

Function

Generate a pseudo-random number.

Explanation

RANDOM generates pseudo-random numbers ranging from 0 to 65535. They're called "pseudo-random" because they appear random, but are generated by a logic operation that uses the initial value in Variable to "tap" into a sequence of 65535 essentially random numbers. If the same initial value, called the "seed", is always used, then the same sequence of numbers is generated. The following example demonstrates this:

SYMBOL  result  = W1

Main:
  result = 11000                        ' set initial "seed" value 
  RANDOM result                         ' generate random number
  DEBUG result                          ' show the result on screen 
  GOTO Main

result  VAR     Word

Main:
  result = 11000                        ' set initial "seed" value 
  RANDOM result                         ' generate random number 
  DEBUG DEC ? result                    ' show the result on screen
  GOTO Main

In this example, the same number would appear on the screen over and over again. This is because the same seed value was used each time; specifically, the first line of the loop sets result to 11000. The RANDOM command really needs a different seed value each time. Moving the "Result =" line out of the loop will solve this problem, as in:

SYMBOL  result  = W1

Setup:
  result = 11000                        ' set initial "seed" value 

Main:
  RANDOM result                         ' generate random number 
  DEBUG result                          ' show the result on screen 
  GOTO Main
  END

result  VAR     Word

Setup:
  result = 11000                        ' set initial "seed" value 

Main:
  RANDOM result                         ' generate random number 
  DEBUG DEC ? result                    ' show the result on screen
  GOTO Main
  END

Here, result is only initialized once, before the loop. Each time through the loop, the previous value of result, generated by RANDOM, is used as the next seed value. This generates a more desirable set of pseudo-random numbers.

In applications requiring more apparent randomness, it's necessary to "seed" RANDOM with a more random value every time. For instance, in the example program, RANDOM is executed continuously (using the previous resulting number as the next seed value) while the program waits for the user to press a button. Since the user can't control the timing of button presses very accurately, the results approach true randomness.

Go to Welcome page

BASIC Stamp Help Version 2.5.4

Copyright © Parallax Inc.

8/8/2012