random()
Return a random number.
Syntax
random([maximum])
Parameter
Parameter | Definition |
---|---|
maximum | optional upper bound for the values returned by random 0 ≤ random() ≤ maximum - 1 *Valid Values* *Default* |
Description
The random() function is equivalent to the standard C library random() function.
If maximum is zero or negative, the random() function will return a run-time error message.
Example
The following example tests the random() function by simulating the rolling of a single six-sided die. If the die (and the random() function) are honest, each of the numbers is equally likely, and after an arbitrarily large number of throws, each will come up an approximately equal number of times:
function main() {
srandom(time()); # seed random() with the system clock
ones = twos = threes = fours = fives = sixes = 0;
limit = 6000;
count = 0;
while (count++ <= limit) {
roll = int(random(6)) + 1;
switch (roll) {
case 1: {ones++;}
case 2: {twos++;}
case 3: {threes++;}
case 4: {fours++;}
case 5: {fives++;}
case 6: {sixes++;}
}
}
expected = int(limit / 6);
print(" expected actual\n");
print(" -------- --------\n");
printf("%2d %8d %8d\n",1,expected,ones);
printf("%2d %8d %8d\n",2,expected,twos);
printf("%2d %8d %8d\n",3,expected,threes);
printf("%2d %8d %8d\n",4,expected,fours);
printf("%2d %8d %8d\n",5,expected,fives);
printf("%2d %8d %8d\n",6,expected,sixes);
}
srandom(time()); # seed random() with the system clock
ones = twos = threes = fours = fives = sixes = 0;
limit = 6000;
count = 0;
while (count++ <= limit) {
roll = int(random(6)) + 1;
switch (roll) {
case 1: {ones++;}
case 2: {twos++;}
case 3: {threes++;}
case 4: {fours++;}
case 5: {fives++;}
case 6: {sixes++;}
}
}
expected = int(limit / 6);
print(" expected actual\n");
print(" -------- --------\n");
printf("%2d %8d %8d\n",1,expected,ones);
printf("%2d %8d %8d\n",2,expected,twos);
printf("%2d %8d %8d\n",3,expected,threes);
printf("%2d %8d %8d\n",4,expected,fours);
printf("%2d %8d %8d\n",5,expected,fives);
printf("%2d %8d %8d\n",6,expected,sixes);
}
The example produces the following output:
expected actual
-------- --------
1 1000 984
2 1000 977
3 1000 1044
4 1000 988
5 1000 1036
6 1000 971
-------- --------
1 1000 984
2 1000 977
3 1000 1044
4 1000 988
5 1000 1036
6 1000 971
Tip: For faster searching, add an asterisk to the end of your partial query. Example: cert*