Chapter 10 – Random Numbers

RANDOMIZE, RND and % RND

This chapter deals with the functions RND, RND () and % RND and the keyword RANDOMIZE. They are all used in connection with random numbers, so you must be careful not to get them mixed up.

As far as normal functions go, RND is quite unusual: although it does calculations and produces a result, it does not need an argument.

Each time you use it, its result is a new random floating point number Sbetween 0 and 1. (Sometimes it can take the value 0, but never 1.)

Try:

10 PRINT RND
20 GO TO 10

to see how the answer varies. Can you detect any pattern? You shouldn't be able to; random means that there is no pattern1.

% RND, which is – as seen on Chapter 8 – the version of RND available in integer expressions, behaves slightly differently. It takes a single argument (e.g. n) and returns a random integer in the range 0 to n-1. For example, %RND 10 will return a random integer between 0 and 9.

While RND returns, as discussed above, a random number between 0 and 1, you can easily get random numbers in other ranges. For instance, 5*RND is between 0 and 5, and 1.3+0.7*RND is between 1.3 and 2. For cases where we need to be in the standard expression evaluator, there is yet another version of RND, which is not an integer expression only function:

RND (n)

which returns a random integer between 0 and n-1 like %RND n. This is recommended over using the standard fractional floating-point function RND since it doesn't suffer from the biasing inherent in converting a fractional random number to an integer with multiply and truncation steps.

To get whole numbers with RND use INT (remembering that INT always rounds down) as in 1+INT (RND*6). If however your desired random values can stay within the range of 0 to 65535, it is better to use % RND or RND() which avoid the unnecessary conversions – and rather slow – floating point calculations involved.

To illustrate better what all version can do, let's use all three of them in a program to simulate dice throwing. RND*6 is in the range 0 to 6, but since it never actually reaches 6, INT (RND*6) is 0,1,2,3,4 or 5.

Here is the dice throwing program:

10 REM dice throwing program
20 CLS
30 FOR n=1 TO 2
40 PRINT 1+INT (RND*6);" ";
50 NEXT n
60 INPUT a$: GO TO 20

1 Actually, RND is not truly random, because it follows a fixed sequence of 65536 numbers. However, these are so thoroughly jumbled up that there are at least no obvious patterns so we say that RND is pseudo-random.


ZX Spectrum Next User Manual, 3rd Edition (ISBN 978-1-5272-5496-1), written and illustrated by Phoebus R. Dokos. Copyright © 2020-2024 Phoebus Dokos / SpecNext Ltd. Licensed under CC BY-NC-SA 4.0. This is a transcription and can contain errors; check any doubt against the printed page.