Tinderbox v10 Icon

rand([maxNumber])


Operator Type: 

Operator Scope of Action: 

Operator Purpose: 

Data Type Returned: 

Operator First Added: 

Operator in Current Baseline: 

Operator Last Altered: 

Operator Has Optional Arguments: 

 Function  [other Function type actions]

 Item  [operators of similar scope]

 Mathematical  [other Mathematical operators]

 Number [about Number data type]

 v4.0.0

 Baseline

 9.5.2

 [More on optional operator arguments]


Syntax note: Operators without any defined mandatory arguments may omit their empty closing parentheses


rand([maxNumber])

rand()

rand

rand() returns a pseudo-random number between 0 and 1. No argument is required.

rand([maxNumber])

Supplying an optional parameter maxNumber, which must be an integer, returns a random integer between 0 and maxNumber-1. This can be useful when wanting random list items, noting that list items are addressed using zero-based integers.

N.B. if working with list-based items, consider the list.randomItem() operator, which abstracts away the need to know the size of the list. Essentially it encapsulates calling list.at(rand(list.count)), so much easier to write/use

Getting 1-based ranges vs. zero-based ranges of values

Consider the original round() method:

$MyNumber=round(rand()*10); 

$MyNumber will be set to one of eleven integers in the range 0 through to 10. But, what if the '10' argument about is actually a child count:

$MyNumber=round(rand()*$ChildCount); 

If the $ChildCount was 10 and $MyNumber were used to fetch a random child using $SiblingOrder($MyNum) the process would fail if $MyNumber were zero as $SiblingOrder numbers from 1. Indeed, in this case the need is for ten integers, one through to ten.

Previously, 1-based range can be achieved:

$MyNumber=round(rand()*(10-1))+1; 
$MyNumber=round(rand()*($ChildCount-1))+1; 

If the main input is 10, by subtracting 1 the process returns a randomised integer in in the range 0-9 (ten numbers) and then adding back 1 shifts the value range to 1-10.

Using the newer rand(maxNumber) method the above becomes:

$MyNumber=round(rand($ChildCount-1))+1; 

This is why the list.randomItem() may be an easier clear approach.


See also—notes linking to here: