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

Here's an example on how to generate a random number between 2 numbers Based on C code, algorithm = randomNumber % ((max + 1) - min) + min Here's the tcl version using rand(): *note Change 100 to 1000 if you want a random number that goes into thousands. etc.. Also the rand() function generates a number between 0 & 1. That's why one would multiply by 10 or 100 or 1000, etc..

Tcl, 6 lines
1
2
3
4
5
6
proc myRand { min max } {
    set maxFactor [expr [expr $max + 1] - $min]
    set value [expr int([expr rand() * 100])]
    set value [expr [expr $value % $maxFactor] + $min]
return $value
}

You would want to use this if you are trying to generate a random number, between a minimum and a maximum.

6 comments

Keith Vetter 18 years, 7 months ago  # | flag

I don't think this code works. The first 'set value' line causes the result to always be between min and min+100.

Kiko The King 18 years, 5 months ago  # | flag

Try this one... i just found the scripting style a big waste of bytes :P

(too many [expr]) u can just use one and use (..) to separate stuff :P

but as they say...style is like ass everyone has his ;)

try this one out...

proc X {m M} {return [expr $m+round(rand()*($M-$m))]}

lets try to explain it ;p

imagine u want to rand between 6 and 10...10-6=4 now randomize between 0 and the result 4...round() instead of int() so we wont need +1 (waste of another operation) supposing u got 3... add MIN to that and there u have ur result :P

Josiah Carlson 17 years, 12 months ago  # | flag

I'm not a Tcl user but... If round works in Tcl like it works in standard mathematics, you don't want to round. Why? Because then you get into a situation where the extremes can happen 1/2 as often as the numbers that are not extreme. For example, you used a range of 6 to 10 inclusive. The ranges that would produce each value are below (adding 6 to produce the 6 to 10).

[0, .5) -> 0

[.5, 1.5) -> 1

[1.5, 2.5) -> 2

[2.5, 3.5) -> 3

[3.5, 4] -> 4

By adding one and taking the int() of a float, you normalize it so that the extremes of 0 and 4 get equivalent size ranges.

Frank Bannon 10 years, 2 months ago  # | flag

The following is a random number generator that returns uniform values between 1 and num:

proc random {{num 10}} {return [expr {int(1 + rand() * $num)}]}
thomas jones 8 years, 7 months ago  # | flag

proc rand_range { min max } { return [expr int(rand() * ($max - $min)) + $min] }

zzc 6 years, 11 months ago  # | flag

the above code should be corrected as:

proc rand_range {min max} { return [expr int(rand()*($max-$min+1)) + $min] }

Created by Dom Lam on Tue, 4 Mar 2003 (MIT)
Tcl recipes (162)
Dom Lam's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks