There are several different ways to generate a random number. I feel I have found the easiest and quickest method, based in system value QTIME.
System value QTIME is a nine-digit field in the format HHMMSSTTT, where HH is the hours, MM is minutes, SS is seconds and TTT is thousandths of a second. The TTT portion changes very rapidly. If you write a program to display these values continually, you would not be able to see them as they change so fast.
The Retrieve Random Number (RTVRNDNBR) command shown in 4, on page 66, returns a three-digit number between .000 and .999, which you can multiply by any whole number in order to obtain a more suitable random number in any range you wish. For example, you can multiply the generated random number by 6 and add 1, truncating any decimal portion. The result is a one-digit whole number between 1 and 6, which you can use to simulate the throw of a die.
The Retrieve Random Number (RTVRNDNBR) command shown in Figure 4, on page 66, returns a three-digit number between .000 and .999, which you can multiply by any whole number in order to obtain a more suitable random number in any range you wish. For example, you can multiply the generated random number by 6 and add 1, truncating any decimal portion. The result is a one-digit whole number between 1 and 6, which you can use to simulate the throw of a die.
Program RND001CL (5, on page 66) retrieves system value QTIME into a nine-digit character field, then uses only the last three digits in reverse order and divides the result by 1000. This is the random number returned by the command.
Program RND001CL (Figure 5, on page 66) retrieves system value QTIME into a nine-digit character field, then uses only the last three digits in reverse order and divides the result by 1000. This is the random number returned by the command.
Editor's Note: For the most theoretically accurate random number generator, see the RPG subroutine RANDSUBR published in the December 1986 article, "Random Number Generator." This subroutine can be downloaded from the OpenBBS. This code was originally published for the System/36 in RPG II. Next month, we will republish the code in RPG/400 for the AS/400 in TechTalk.
TechTalk: Random Number Generator
Figure 4 Command RTVRNDNBR
RTVRNDNBR: CMD PROMPT('Retrieve Random Number') PARM KWD(RNDNBR) TYPE(*DEC) LEN(3 3) RTNVAL(*YES) + CHOICE('DEC(3 3)') PROMPT('Random + number: .000 to .999')
TechTalk: Random Number Generator
Figure 5 CL program RND001CL
RND001CL: + PGM PARM(&RNDNBR) DCL VAR(&LAST_3C) TYPE(*CHAR) LEN(3) DCL VAR(&LAST_3D) TYPE(*DEC) LEN(3 0) DCL VAR(&RNDNBR) TYPE(*DEC) LEN(3 3) DCL VAR(&SYSTIME) TYPE(*CHAR) LEN(9) RTVSYSVAL SYSVAL(QTIME) RTNVAR(&SYSTIME) CHGVAR VAR(&LAST_3C) VALUE(%SST(&SYSTIME 9 1) *CAT %SST(&SYSTIME + 8 1) *CAT %SST(&SYSTIME 7 1)) CHGVAR VAR(&LAST_3D) VALUE(&LAST_3C) CHGVAR VAR(&RNDNBR) VALUE(&LAST_3D / 1000) ENDPGM
LATEST COMMENTS
MC Press Online