InterSystems IRIS Data Platform 2019.2  /  ObjectScript Reference

ObjectScript Reference
Previous section           Next section
InterSystems: The power behind what matters   

Returns a pseudo-random integer value in the specified range.
range A nonzero positive integer used to specify the upper bound of the range of possible random numbers.
$RANDOM returns a pseudo-random integer value between 0 and range-1 (inclusive). Thus $RANDOM(3) returns 0, 1, 2, but not 3. Returned numbers are uniformly distributed across the specified range.
$RANDOM is sufficiently random for most purposes. Applications that require strictly random values should use the GenCryptRand() method of the %SYSTEM.Encryption class.
This value specifies the upper bound of the range of possible random numbers; the highest random number being range minus 1. The range value can be a nonzero positive integer value, the name of an integer variable, or any valid ObjectScript expression that evaluates to a nonzero positive integer. The maximum range value is 1E17 (100000000000000000); specifying a value beyond this maximum results in a <FUNCTION> error. $RANDOM(1) is valid, but always returns 0. $RANDOM(0) results in a <FUNCTION> error.
The following example returns a random number from 0 through 24 (inclusive).
To return a random number with a fractional portion, you can use the concatenation operator (_) or the addition operator (+), as shown in the following example:
   SET x=$RANDOM(10)_$RANDOM(10)/10
   WRITE !,x
   SET y=$RANDOM(10)+($RANDOM(10)/10)
   WRITE !,y
This program returns numbers with one fractional digit, ranging between .0 and 9.9 (inclusive). Using either operator, InterSystems IRIS deletes any leading and trailing zeros (and the decimal point, if the fractional portion is zero). However, if both $RANDOM functions return zero (0 and .0), InterSystems IRIS returns a zero (0).
The following example simulates the roll of two dice:
   FOR {
      READ "Roll dice? ",reply#1
      IF "Yy"[reply,reply'="" {
         WRITE !,"Pair of dice: "
         WRITE $RANDOM(6)+1,"+",$RANDOM(6)+1,! }
      ELSE { QUIT }

Previous section           Next section
Send us comments on this page
View this book as PDF   |  Download all PDFs
Copyright © 1997-2019 InterSystems Corporation, Cambridge, MA
Content Date/Time: 2019-08-20 05:45:45