COBOL RANDOM Function Examples

COBOL RANDOM Function generates the random fractional values ranging from 0 to 1. It generates values like 0.xxx

For example if we declared the variable as below

01 WW-RANDOM-NUMBERS PIC 99.999 VALUE ZEROES.

PERFORM VARYING WW-SUB1 FROM 1 BY 1 UNTIL WW-SUB1 > 9
COMPUTE WW-RANDOM-NUMBERS = FUNCTION RANDOM
DISPLAY ‘–>’WW-RANDOM-NUMBERS
END-PERFORM

Result:
–>00.443
–>00.060
–>00.805
–>00.170
–>00.916
–>00.487
–>00.296
–>00.746
–>00.298

If declaration is for 6 decimal values then
01 WW-RANDM-NUM PIC 99.999999 VALUE ZEROES.

Result:

RANDOM NUMBER
–>00.442707
–>00.060083
–>00.804784
–>00.170051
–>00.915883
–>00.486698
–>00.296243
–>00.746409
–>00.298420

If there is no decimal value declared, the result gets rounded to either 0 or 1.

PERFORM VARYING WW-SUB1 FROM 1 BY 1 UNTIL WW-SUB1 > 9
COMPUTE WW-RANDOM-NUM = FUNCTION RANDOM(ww-sub1)
DISPLAY ‘–>’WW-RANDM-NUM
END-PERFORM

Result:
–>00.885414
–>00.328121
–>00.770829
–>00.213536
–>00.656243
–>00.098950
–>00.541657
–>00.984364
–>00.427072

So to generate the random positive integers.(ex:1, 2,3..etc), the above decimal fractions needs to be multiplied with a suitable factor.

To get the values between 0 and 20, These factors needs to be multiplied with 20 so that the resultant numbers would be less than 20 and greater than or equal to 0. According to the requirement of numbers to be generated the multiplication factor needs to be chosen.

IBM language reference has few more details on this function and this link can be found here

IBM Reference

If you have any more details on this , please post it via comments.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami