Random Numbers in COBOL

Our program will demonstrate generating random numbers. Here’s the full source code:

       IDENTIFICATION DIVISION.
       PROGRAM-ID. RANDOM-NUMBERS.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-RANDOM-INT PIC 9(3).
       01 WS-RANDOM-FLOAT PIC 9V9(9).
       01 WS-SCALED-FLOAT PIC 9V9(9).
       
       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           PERFORM GENERATE-RANDOM-INTEGERS
           PERFORM GENERATE-RANDOM-FLOATS
           PERFORM GENERATE-SEEDED-RANDOMS
           STOP RUN.

       GENERATE-RANDOM-INTEGERS.
           PERFORM 2 TIMES
               COMPUTE WS-RANDOM-INT = FUNCTION RANDOM * 100
               DISPLAY WS-RANDOM-INT WITH NO ADVANCING
               IF WS-RANDOM-INT < 99
                   DISPLAY "," WITH NO ADVANCING
               END-IF
           END-PERFORM
           DISPLAY SPACE.

       GENERATE-RANDOM-FLOATS.
           COMPUTE WS-RANDOM-FLOAT = FUNCTION RANDOM
           DISPLAY WS-RANDOM-FLOAT
           PERFORM 2 TIMES
               COMPUTE WS-SCALED-FLOAT = (FUNCTION RANDOM * 5) + 5
               DISPLAY WS-SCALED-FLOAT WITH NO ADVANCING
               IF WS-SCALED-FLOAT < 9.9
                   DISPLAY "," WITH NO ADVANCING
               END-IF
           END-PERFORM
           DISPLAY SPACE.

       GENERATE-SEEDED-RANDOMS.
           MOVE FUNCTION CURRENT-DATE(12:2) TO WS-RANDOM-INT
           PERFORM 2 TIMES
               COMPUTE WS-RANDOM-INT = FUNCTION RANDOM(WS-RANDOM-INT) * 100
               DISPLAY WS-RANDOM-INT WITH NO ADVANCING
               IF WS-RANDOM-INT < 99
                   DISPLAY "," WITH NO ADVANCING
               END-IF
           END-PERFORM
           DISPLAY SPACE.

This COBOL program demonstrates the generation of random numbers:

  1. GENERATE-RANDOM-INTEGERS generates two random integers between 0 and 99.

  2. GENERATE-RANDOM-FLOATS generates a random float between 0 and 1, then generates two random floats between 5 and 10.

  3. GENERATE-SEEDED-RANDOMS uses the current seconds as a seed to generate two random integers between 0 and 99.

To run the program, compile the COBOL code and execute the resulting program:

$ cobc -x -free random-numbers.cob
$ ./random-numbers
68,56
0.809022813
5.840125017,6.937056298
94,49

Note that the generated numbers may be different when you run the sample.

In COBOL, we use the FUNCTION RANDOM to generate random numbers. Without arguments, it returns a float between 0 and 1. With an integer argument, it uses that as a seed.

COBOL doesn’t have built-in support for different random number generators like PCG. For more complex random number generation, you might need to implement custom algorithms or use external libraries.