ActiveState Code

Recipe 68391: Random number in a range


Tcl 8.0 added the rand() expr function. Here's a simple way to return the random number in a range.

Tcl
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# random --
#
#	Return a number in the range 0 .. $range-1
#
# Arguments:
#	range    integer range constraint
#
# Results:
#	Number in range [0..$range)
#
proc random {{range 100}} {
    return [expr {int(rand()*$range)}]
}

Discussion

Tcl's rand() function is tied to the system's C rand() implementation. This is a pseudo-random number generated not at all meant to be of cryptographic quality. See http://mini.net/tcl/1549.html for more background information.

Comments

  1. 1. At 2:46 p.m. on 12 dec 2001, Don Porter said:

    Tcl does not call C's rand(). The discussion is incorrect. Tcl implements its own pseudo-random number generator. It does not call the system rand().

Sign in to comment