Tcl Mathematical Expressions

In Tcl, mathematical expressions are evaluated using the expr command. This command works with integers, floating point values and logical (Boolean) values. There are many arithmetic operators and built-in math functions in Tcl.

For more in-depth explanations and a complete listing, referred to http://www.tcl.tk/man/ or to a Tcl/Tk handbook.

An example of calculating the circumference of a circle with radius of 6:
set circumference [expr 2*(2*asin(1.0))*6.0]
puts $circumference
37.6991118431
Variable references can be used with the expr command as well.
set pi [expr 2*asin(1.0)]
set radius 6.0
set circumference [expr 2*$pi*$radius]
puts $circumference
37.6991118431
It is also possible to use nested commands inside of expr.
set pi [expr 2*asin(1.0)]
set radius "radius"
set circumference [expr 2*$pi*[string length $radius]]
puts $circumference
37.6991118431
It is important to notice the difference between using integer values and floating point values when doing arithmetic operations.
set using_integer [expr 1/9]
set using_float [expr 1/9.]
puts $using_int
0

puts $using_float
0.111111111111
It is recommended practice to use curly braces to group expr commands and improve the efficiency of the Tcl byte code compiler. This helps to preserve the precision that may be lost by converting between strings and numeric values. This in turn speeds up the evaluation of the expression.
set circumference [expr {2*(2*asin(1.0))*6.0}]

set pi [expr {2*asin(1.0)}]
set radius 6.0
set circumference [expr {2*$pi*$radius}]
It also eliminates the possibility of not getting an expected value returned due to the precision lost in the string to numeric value conversion.
set var1 [expr {sqrt(2.0)}]
puts $var1
1.41421356237

set var2 [expr $var1 * $var1]
puts $var2
1.99999999999

set var2 [expr {$var1 * $var1}]
puts $var2
2.0
In HyperWorks, the default number of significant digits returned is 12. The Tcl variable tcl_precision allows you to query and set the number of significant digits returned.
puts $tcl_precision
12

set var1 [expr 1/9.]
0.111111111111
 
set tcl_precision 17
puts $tcl_precision
17

set var1 [expr 1/9.]
0.11111111111111111