Return to the RPG Tips
Random Number Generators
RANDOM NUMBER GENERATOR IN RPG IV The RPG IV program below supports the math bindable API CEERAN0 (Basic Random Number Generation). The input parameter C0Seed has a valid range of 0 to 2,147,483,646; when the value is 0, the API generates a seed from the system's current Greenwich mean time. On return, CEERAN0 changes the value so it can be used as the new seed in a subsequent call. Output parameter C0RndNbr is a 64-bit double floating-point number with a value between 0 and 1. If an invalid seed is used, -1 is returned. The program logic is based on the minimum and maximum values for the random number generation. These values are initialized in the D-specs. The program uses the %DecH built-in function to convert the floating- point random number into a packed decimal with a length of 30 digits and 29 decimal positions. It then multiplies this value by the maximum value: Because 1 is the highest possible random number, the result will never be greater than the maximum value. The program's Do loop ensures that the random number generation is repeated until the result is higher than or equal to the minimum value. D C0Seed S 10I 0 Inz(0) D C0RndNbr S 8F **-- Random Number Conversion: ---------------------------------- ** D RndNbr S 10I 0 D MaxNbr S 10I 0 Inz(9000000) D MinNbr S 10I 0 Inz(1000000) ** **==================================================================** ** C DoU RndNbr >= MinNbr ** C CallB 'CEERAN0' C Parm C0Seed C Parm C0RndNbr C Parm *OMIT ** C Eval RndNbr = %DecH(C0RndNbr:30:29) * MaxNbr C EndDo ** C Return RANDOM NUMBER GENERATOR IN ILE CL (OPM callable) /*------------------------------------------------------------------*/ /* Generates a random number between 0 and 1. */ /* This is a bound ILE CLP program and requires these compile steps */ /* 1. CRTCLMOD */ /* 2. CRTPGM RANDOM MODULE(RANDOM) SRVPGM(QLEMF) */ /* */ /* The first parameter is returned as a FLOAT8 (aka FLOAT BIN(53)) */ /* The second is a seed value. After, the SEED value is modified by */ /* this program. */ /*------------------------------------------------------------------*/ RANDOM: PGM (&RTNVAL &SEED) DCL &RTNVAL *CHAR (8) DCL &SEED *CHAR (4) CALLPRC PRC(CEERAN0) PARM(&SEED &RTNVAL) ENDPGM .
[report a broken link by clicking here]