The Random Function in COBOL

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.
A random number generator in COBOL aids statistical calculations.
Image Credit: Hemera Technologies/ Images

The COBOL programming language, one of the oldest still in regular use, has a strong bias toward business applications, such as accounting, payroll and inventory control. However, newer versions of COBOL have sophisticated mathematical functions, including one for generating random numbers. Though seldom used for day-to-day business accounting, random numbers help facilitate statistical calculations and certain kinds of numerical problem-solving techniques.



COBOL math functions are part of the language's procedure division, the section of the program consisting of procedural statements. Functions begin with the reserved word "function" followed by the function name, such as "cos," "random" or "log." A function takes one or more arguments, performs a process on them and returns a result back to the COBOL program. Some functions work on numbers and numeric variables, while others work on character data.


Video of the Day


The random function takes a non-negative integer argument and returns a decimal number. The integer argument is optional. It is the seed for a pseudo-random mathematical process, that determines the function's first returned number. In computer languages, all random processes are in fact long, repeating series of numbers that appear to be random. A well-chosen process repeats only after billions of values, so it is a practical source of random numbers, even if it is not a theoretically pure one. If you supply the random function with an argument, it will generate the same sequence of numbers. Without the argument, the random function generates the next number in its sequence.


Range and Distribution

The random function in COBOL returns decimal numbers in a range of zero through one. Statistically, the random numbers have a rectangular distribution, meaning each number is equally likely. A graph of a long series of random numbers will have a relatively flat line extending from zero to almost one. This contrasts with the normal, or Gaussian, distribution, which forms a bell-shaped curve.



By themselves, random function decimal numbers are not very useful, but if you multiply them by a scaling factor, you create a range of random numbers suitable for your application. For example, to obtain random integers between one and 52, you would use the following COBOL statement: COMPUTE RANDOM-VALUE = FUNCTION RANDOM (1) * 52 + 1.


In the statement, the random function generates numbers greater than or equal to zero and less than one. Multiplying this by 52 gives you numbers between zero and 51. Adding one gives you the range of one to 52.




Report an Issue

screenshot of the current page

Screenshot loading...