Jump to content

BASIC Programming/Random Number Generation

From Wikibooks, open books for an open world

One useful thing for games is random numbers. This is a sequence of numbers that appears randomly distributed, so they can be used to simulate things like shuffling a deck of cards or producing different behaviours every time a program runs.

Random numbers in BASIC are generated by the RND function. This returns a number between 0 and 1. For example:

PRINT "Wikibooks' coolness quotient: ", RND, "%"

You will get "Wikibooks' coolness quotient: .7055475%".

That result looks random. Run it again and you get the same value! That makes a game boring. This is the purpose of seeding, which is normally accomplished with the RANDOMIZE statement. In modern dialects, this can be tied to the clock using the TIMER keyword:

RANDOMIZE TIMER
PRINT "Wikibooks' coolness quotient: ", RND, "%"

which will print "Wikibooks' coolness quotient: .8532526%" and another time will print "Wikibooks' coolness quotient: .3582422%". Better, right?

But decimal numbers are not always useful. If you want a whole number, you must get a random number and then convert it to a whole number. Normally you want that number to be between two limits, say 0 and 100. One solution is to take the number, multiply by the maximum desired value, add half to round it, and then take the whole number part. Some slight variation on the following code is very common:

PER = INT(RND() * 99 + 0.5)

Modern dialects like QBASIC offer more control. We can state the variable is an integer, and BASIC will force it to that format and slightly simplify the code:

RANDOMIZE TIMER
DIM PER AS INTEGER
PER = RND * 100 + 0.5
PRINT "Wikibooks' coolness quotient: ", PER, "%"

which will print "Wikibooks' coolness quotient: 85%".