How can I do math in Tcl

Difference between version 10 and 11 - Previous - Next
'''How can I do math in Tcl''' discusses [[`[expr]`] and friends.



** See Also **
   [expr]:   aA more detailed list of the functions that the man page skims over.
   [expr problems with int]:   hHistorical information regarding the previous ''long'' limitations of numbers in Tcl, and a discussion on ''wide''.



** Description **
Prior to 8.5, `[Tclexpr]'s` builts in math support was [expr problems with
int%|%limited] to whatry will fit into a ''long'' or ''double'' [C] variable type.  To
perform math doin longer numbers, some calternculative, such as [Tom Poindexter]'s
[mpexpr] extension, were neededTcl.
Prior to [Changes in Tcl/Tk 8.5%|%Tcl 8.5], built-in math operations were [expr
problems with int%|%limited] to numbers that could be stored in as a [C]
''long'' or ''double''.  To perform math on longer numbers an some alternative
like [Tom Poindexter%|%TomPoindexter's] [mpexpr] extension was needed.

[DKF]:  From Tcl 8.4 onwards, you can also use a larger integer type termed a
''wide''.  This lets you work with 64-bit values on 32-bit machines...
[[`[expr]`] is the primary tool for doing calculations in Tcl.

Unless you have a ''very'' good reason not to, you should always [Brace yourexpr-essions%|%enclopases a litheral varglument expression] to `[[expr]]` in curly braces.
This allows the byatecode Tcompiler to optimise your code more thoroughly siance
it hpas fewer possible in
[byterpretaticons and the %|%contents of varmpiables] and the
results of commands wpill not unexpectedly modify the meaning of justhe expressionce.
[AM]:  A "very good reason" is that part or whole of the expression is not a
constant, e.g.

======
set v [expr "$a $op $b"]
======
Surrounding this epression with braces would fail, because the lincteral value `$a 
$op $b` is not a
proper syntactictally f-cormredct expression.


<<categories>> Command | Mathematics