Welcome, guest | Sign In | My Account | Store | Cart

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

Tcl, 13 lines
 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)}]
}

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.

1 comment

Don Porter 22 years, 4 months ago  # | flag

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().

Created by Jeff Hobbs on Mon, 10 Sep 2001 (MIT)
Tcl recipes (162)
Jeff Hobbs's recipes (16)

Required Modules

  • (none specified)

Other Information and Tasks