RANDOM Seed {, Duplicate}

Function
Generate a pseudo-random number.

Explanation
RANDOM generates pseudo-random numbers ranging from 0 to 255 (if Seed is a byte) or 0 to 65535 (if Seed is a word). The value is called "pseudo-random" because it appears random, but are generated by a logic operation that uses the initial value in Seed to "tap" into a sequence of essentially random numbers. If the same initial value, called the "seed", is always used, then the same sequence of numbers will be generated. The following example demonstrates this:

Start:
  TRIS_B = %00000000                            ' make RB outputs (LEDs)

Main:
  DO
    result = 123                                ' set initial "seed" value 
    RANDOM result                               ' generate random number
    RB = result                                 ' show the result on RB 
    PAUSE 100
  LOOP

In this example, the same number would appear on RB 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 123. 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:

Start:
  TRIS_B = %00000000                            ' make RB outputs (LEDs)

Main:
  result = 123                                  ' set initial "seed" value 
  DO
    RANDOM result                               ' generate random number
    RB = result                                 ' show the result on RB 
    PAUSE 100
  LOOP

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 digital dice 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.


Related project: Digital Dice