23.2: Generating Random Number
- Page ID
- 54396
To request a random number, a real variable must be declared and then passed to the following call to the built-in random_number()
routine. For example:
call random_number(x)
The random number between 0.0 and 1.0 such that 0.0 \(\leq\) random number \(<\) 1.0.
In order to obtain a larger number, it can be multiplied by an appropriate scale. For example, to simulating the roll of a dice, a random integer number between 1 and 6 would be required. The following code would obtain the random number and then scale it and convert to integer as required.
call random_number(x) die = int(x*6.0) + 1
Since the 0.0 is a possible value and 1.0 is not ( 0.0 \(\leq\) random number \(<\) 1.0) 1 is added to ensure that 0 cannot be assigned to the variable die
. Further, since .999 is the largest possible value (since 1.0 is not), and .999 * 6 will generate 6 (5.9 truncated to 5 with 1 added).