Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Python, Lua and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Java, C, C++, Ruby, MySQL and Linux / Tomcat systems
Random Number generator

Posted by kinshuk_mishra (kinshuk_mishra), 17 March 2004

I want to know how to generate random numbers in TCL if some range is given. I can do that in K shell but I am unable to do that in TCL.

For example.
If i give two numbers say 100 and 100000 then between this the script should generate random numbers and the numbers generated should not be repeated. I am unable to do this.

Please help

Thanks in advance


Posted by Custard (Custard), 17 March 2004
A quick glance at Dr Google returns:

Hope this helps.


(ps. it's not my code, just the first result..)

Posted by admin (Graham Ellis), 17 March 2004
The rand function generates a random number between 0 and 1. Multiply the value it returns by the range you require, and add the offset you need, and convert to an integer.  Thus

set value [expr floor( rand() * 999900) + 100]

You can run this again and you'll get a second number but there is a 1 in 999900 chance it will be the same number - you say you don't want this, so you should probably code a loop to keep asking for another random number until you meet your criterion.

Edit - hey, Custard, thanks for your answer.  I started writing mine at lunchtime and got dragged away to do some training - just came back a moment ago and finished my doodlings - didn't meet to step on your toes

Posted by Custard (Custard), 17 March 2004
It's fine Graham.  (glad to hear your keeping busy)

To be honest it's been a while since I last TCLed. I had a feeling there was a rand proc. but the link above was the first relevant google for 'random and tcl'

Your solution is much more elegant.


This page is a thread posted to the opentalk forum at and archived here for reference. To jump to the archive index please follow this link.

2 unpublished comments pending on this page

edit your own (not yet published) comments

© WELL HOUSE CONSULTANTS LTD., 2018: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: • WEB: • SKYPE: wellho