The function [tt]
RND[/tt] returns a random number between 0 and 1 (in the form of a decimal number). [tt]
RND[/tt] can return 0, but it never returns 1. [tt]
INT(x)[/tt] truncates the decimal part of [tt]x[/tt], so [tt]
INT(
RND * n)[/tt] can be used to acquire an integer in the range [0,n-1].
The way [tt]
RND[/tt] works is by multiplying a stored integer by a very large number and then taking the modulus of the result against another large number that is coprime to the other large number. The result is stored for next time, then divided by the second large number and returned to you. This means that the initial value of that stored number predetermines the sequence of "random" numbers you will get. For this reason, they are called
pseudo-random numbers, and functions like [tt]
RND[/tt] are referred to as
pseudo-random number generators. Thus arises the issue of to what that initial value, called the
seed, should be set. The QB function [tt]
RANDOMIZE n[/tt] sets the random number seed to the floating-point number [tt]n[/tt]. In theory, this should mean that if you [tt]
RANDOMIZE[/tt] twice with the same number, you should get the same sequence of pseudorandom numbers. In practice, this is not the case. I'm not sure why, but if you want to generate pseudorandom numbers whose sequence can be set by specifying specific seeds, you'll have to write your own random number generator. The problem of picking good multipliers and dividers is a well-discussed problem in certain mathematical circles. Badly-chosen numbers do not provide a properly random distribution. In any case, write a program to test your random number generator's distribution, and experiment until you get an even distribution.
In general, though, repeated sequences of pseudorandom numbers are not desired. To ensure that the sequence is NOT the same, a common practice is to seed the pseudorandom number generator with a number derived from the current system time. The easiest way to do this in QuickBASIC is:
[tt]
RANDOMIZE TIMER[/tt]
To summarize, a quick program to output 5 random numbers:
[tt]
RANDOMIZE TIMER
PRINT "A random number in the range [0,1):"
PRINT RND
PRINT "A random integer in the range [0,10) ([0,9]):"
PRINT INT(
RND * 10)
PRINT "A random integer in the range [1,10]:"
PRINT INT(
RND * 10 + 1)
n% = 5
PRINT "A random integer in the range [";
STR$(-n%); ",";
LTRIM$(
STR$(n%)); "]:"
PRINT INT(
RND * (n% * 2 + 1) - n%)
m! = 3.5
PRINT "A random integer in the range [";
STR$(-m!); ",";
LTRIM$(
STR$(m!)); "

:"
PRINT (
RND * (m! * 2) - m!)