Friday, October 12, 2012

Use of RND

Generating random numbers is something we frequently call upon computers to do. You can simulate the result of flipping a coin, rolling dice, or selecting lottery numbers. To do so in BASIC, we use the RND function.

The syntax is

RND

This tiny bit of code returns a number between 0 and 1 but that isn't all that handy, now is it? We have to do a bit of tweaking to get integers.

If you want your answer as a one or a two, use this code

INT( RND * 2 )

The bit inside the parentheses

RND * 2

will generate a number between 0 and just less than 2.

Applying the typecast INT will cause the value to be truncated - meaning the decimal portion gets lopped off so you get either a 0 or a 1 from

INT( RND * 2 )

Let's say you want to mimic the roll of a die. The most common die is a six-sided cube but there are plenty of other types: 4-sided, 8-sided, 12-sided, 20-sided, etc. We shall "roll" an 8-sided die.

The code

INT( RND * 8 + 1 )

generates our random number. Adding the one in there forces the values returned to range from 1 to 8 instead of from 0 to 7.

We can simply print our random number like this

PRINT INT( RND * 8 + 1 )

or we can use the value obtained to assign a value to a variable like this

a = INT( RND * 8 + 1 )

or even to do comparisons between two values (we'll see this later).

NOTE
In order to get the numbers to be as random as possible, we insert the code

RANDOMIZE TIMER

before we make our first call to RND. If we forget this step, we get the same "random" series every time.