Initial version of donated sources by Avertec, 3.4p5.
[tas-yagle.git] / distrib / share / tcl / help / tcl / math / expr
1 NAME
2 expr - Evaluate an expression
3
4 SYNOPSIS
5 expr arg ?arg arg ...?
6
7
8 DESCRIPTION
9 Concatenates args (adding separator spaces between them), evaluates the
10 result as a Tcl expression, and returns the value. The operators per-
11 mitted in Tcl expressions are a subset of the operators permitted in C
12 expressions, and they have the same meaning and precedence as the cor-
13 responding C operators. Expressions almost always yield numeric
14 results (integer or floating-point values). For example, the expres-
15 sion
16 expr 8.2 + 6
17 evaluates to 14.2. Tcl expressions differ from C expressions in the
18 way that operands are specified. Also, Tcl expressions support non-
19 numeric operands and string comparisons.
20
21 OPERANDS
22 A Tcl expression consists of a combination of operands, operators, and
23 parentheses. White space may be used between the operands and opera-
24 tors and parentheses; it is ignored by the expression's instructions.
25 Where possible, operands are interpreted as integer values. Integer
26 values may be specified in decimal (the normal case), in octal (if the
27 first character of the operand is 0), or in hexadecimal (if the first
28 two characters of the operand are 0x). If an operand does not have one
29 of the integer formats given above, then it is treated as a floating-
30 point number if that is possible. Floating-point numbers may be speci-
31 fied in any of the ways accepted by an ANSI-compliant C compiler
32 (except that the f, F, l, and L suffixes will not be permitted in most
33 installations). For example, all of the following are valid floating-
34 point numbers: 2.1, 3., 6e4, 7.91e+16. If no numeric interpretation
35 is possible (note that all literal operands that are not numeric or
36 boolean must be quoted with either braces or with double quotes), then
37 an operand is left as a string (and only a limited set of operators may
38 be applied to it).
39
40 On 32-bit systems, integer values MAX_INT (0x7FFFFFFF) and MIN_INT
41 (-0x80000000) will be represented as 32-bit values, and integer values
42 outside that range will be represented as 64-bit values (if that is
43 possible at all.)
44
45 Operands may be specified in any of the following ways:
46
47 [1] As a numeric value, either integer or floating-point.
48
49 [2] As a boolean value, using any form understood by string is
50 boolean.
51
52 [3] As a Tcl variable, using standard $ notation. The variable's
53 value will be used as the operand.
54
55 [4] As a string enclosed in double-quotes. The expression parser
56 will perform backslash, variable, and command substitutions on
57 the information between the quotes, and use the resulting value
58 as the operand
59
60 [5] As a string enclosed in braces. The characters between the open
61 brace and matching close brace will be used as the operand with-
62 out any substitutions.
63
64 [6] As a Tcl command enclosed in brackets. The command will be exe-
65 cuted and its result will be used as the operand.
66
67 [7] As a mathematical function whose arguments have any of the above
68 forms for operands, such as sin($x). See below for a list of
69 defined functions.
70
71 Where the above substitutions occur (e.g. inside quoted strings), they
72 are performed by the expression's instructions. However, the command
73 parser may already have performed one round of substitution before the
74 expression processor was called. As discussed below, it is usually
75 best to enclose expressions in braces to prevent the command parser
76 from performing substitutions on the contents.
77
78 For some examples of simple expressions, suppose the variable a has the
79 value 3 and the variable b has the value 6. Then the command on the
80 left side of each of the lines below will produce the value on the
81 right side of the line:
82 expr 3.1 + $a 6.1
83 expr 2 + "$a.$b" 5.6
84 expr 4*[llength "6 2"] 8
85 expr {{word one} < "word $a"}0
86
87 OPERATORS
88 The valid operators are listed below, grouped in decreasing order of
89 precedence:
90
91 - + ~ ! Unary minus, unary plus, bit-wise NOT, logical NOT.
92 None of these operators may be applied to string
93 operands, and bit-wise NOT may be applied only to
94 integers.
95
96 * / % Multiply, divide, remainder. None of these opera-
97 tors may be applied to string operands, and remain-
98 der may be applied only to integers. The remainder
99 will always have the same sign as the divisor and
100 an absolute value smaller than the divisor.
101
102 + - Add and subtract. Valid for any numeric operands.
103
104 << >> Left and right shift. Valid for integer operands
105 only. A right shift always propagates the sign
106 bit.
107
108 < > <= >= Boolean less, greater, less than or equal, and
109 greater than or equal. Each operator produces 1 if
110 the condition is true, 0 otherwise. These opera-
111 tors may be applied to strings as well as numeric
112 operands, in which case string comparison is used.
113
114 == != Boolean equal and not equal. Each operator pro-
115 duces a zero/one result. Valid for all operand
116 types.
117
118 eq ne Boolean string equal and string not equal. Each
119 operator produces a zero/one result. The operand
120 types are interpreted only as strings.
121
122 & Bit-wise AND. Valid for integer operands only.
123
124 ^ Bit-wise exclusive OR. Valid for integer operands
125 only.
126
127 | Bit-wise OR. Valid for integer operands only.
128
129 && Logical AND. Produces a 1 result if both operands
130 are non-zero, 0 otherwise. Valid for boolean and
131 numeric (integers or floating-point) operands only.
132
133 || Logical OR. Produces a 0 result if both operands
134 are zero, 1 otherwise. Valid for boolean and
135 numeric (integers or floating-point) operands only.
136
137 x?y:z If-then-else, as in C. If x evaluates to non-zero,
138 then the result is the value of y. Otherwise the
139 result is the value of z. The x operand must have
140 a boolean or numeric value.
141
142 See the C manual for more details on the results produced by each oper-
143 ator. All of the binary operators group left-to-right within the same
144 precedence level. For example, the command
145 expr 4*2 < 7
146 returns 0.
147
148 The &&, ||, and ?: operators have ``lazy evaluation'', just as in C,
149 which means that operands are not evaluated if they are not needed to
150 determine the outcome. For example, in the command
151 expr {$v ? [a] : [b]}
152 only one of [a] or [b] will actually be evaluated, depending on the
153 value of $v. Note, however, that this is only true if the entire
154 expression is enclosed in braces; otherwise the Tcl parser will evalu-
155 ate both [a] and [b] before invoking the expr command.
156
157 MATH FUNCTIONS
158 Tcl supports the following mathematical functions in expressions, all
159 of which work solely with floating-point numbers unless otherwise
160 noted:
161
162 abs cosh log sqrt
163 acos double log10 srand
164 asin exp pow tan
165 atan floor rand tanh
166 atan2 fmod round wide
167 ceil hypot sin
168 cos int sinh
169
170
171
172 abs(arg)
173 Returns the absolute value of arg. Arg may be either integer or
174 floating-point, and the result is returned in the same form.
175
176 acos(arg)
177 Returns the arc cosine of arg, in the range [0,pi] radians. Arg
178 should be in the range [-1,1].
179
180 asin(arg)
181 Returns the arc sine of arg, in the range [-pi/2,pi/2] radians.
182 Arg should be in the range [-1,1].
183
184 atan(arg)
185 Returns the arc tangent of arg, in the range [-pi/2,pi/2] radi-
186 ans.
187
188 atan2(y, x)
189 Returns the arc tangent of y/x, in the range [-pi,pi] radians.
190 x and y cannot both be 0. If x is greater than 0, this is
191 equivalent to atan(y/x).
192
193 ceil(arg)
194 Returns the smallest integral floating-point value (i.e. with a
195 zero fractional part) not less than arg.
196
197 cos(arg)
198 Returns the cosine of arg, measured in radians.
199
200 cosh(arg)
201 Returns the hyperbolic cosine of arg. If the result would cause
202 an overflow, an error is returned.
203
204 double(arg)
205 If arg is a floating-point value, returns arg, otherwise con-
206 verts arg to floating-point and returns the converted value.
207
208 exp(arg)
209 Returns the exponential of arg, defined as e**arg. If the
210 result would cause an overflow, an error is returned.
211
212 floor(arg)
213 Returns the largest integral floating-point value (i.e. with a
214 zero fractional part) not greater than arg.
215
216 fmod(x, y)
217 Returns the floating-point remainder of the division of x by y.
218 If y is 0, an error is returned.
219
220 hypot(x, y)
221 Computes the length of the hypotenuse of a right-angled triangle
222 sqrt(x*x+y*y).
223
224 int(arg)
225 If arg is an integer value of the same width as the machine
226 word, returns arg, otherwise converts arg to an integer (of the
227 same size as a machine word, i.e. 32-bits on 32-bit systems, and
228 64-bits on 64-bit systems) by truncation and returns the con-
229 verted value.
230
231 log(arg)
232 Returns the natural logarithm of arg. Arg must be a positive
233 value.
234
235 log10(arg)
236 Returns the base 10 logarithm of arg. Arg must be a positive
237 value.
238
239 pow(x, y)
240 Computes the value of x raised to the power y. If x is nega-
241 tive, y must be an integer value.
242
243 rand() Returns a pseudo-random floating-point value in the range (0,1).
244 The generator algorithm is a simple linear congruential genera-
245 tor that is not cryptographically secure. Each result from rand
246 completely determines all future results from subsequent calls
247 to rand, so rand should not be used to generate a sequence of
248 secrets, such as one-time passwords. The seed of the generator
249 is initialized from the internal clock of the machine or may be
250 set with the srand function.
251
252 round(arg)
253 If arg is an integer value, returns arg, otherwise converts arg
254 to integer by rounding and returns the converted value.
255
256 sin(arg)
257 Returns the sine of arg, measured in radians.
258
259 sinh(arg)
260 Returns the hyperbolic sine of arg. If the result would cause
261 an overflow, an error is returned.
262
263 sqrt(arg)
264 Returns the square root of arg. Arg must be non-negative.
265
266 srand(arg)
267 The arg, which must be an integer, is used to reset the seed for
268 the random number generator of rand. Returns the first random
269 number (see rand()) from that seed. Each interpreter has its
270 own seed.
271
272 tan(arg)
273 Returns the tangent of arg, measured in radians.
274
275 tanh(arg)
276 Returns the hyperbolic tangent of arg.
277
278 wide(arg)
279 Converts arg to an integer value at least 64-bits wide (by sign-
280 extension if arg is a 32-bit number) if it is not one already.
281
282 In addition to these predefined functions, applications may define
283 additional functions using Tcl_CreateMathFunc().
284
285 TYPES, OVERFLOW, AND PRECISION
286 All internal computations involving integers are done with the C type
287 long, and all internal computations involving floating-point are done
288 with the C type double. When converting a string to floating-point,
289 exponent overflow is detected and results in a Tcl error. For conver-
290 sion to integer from string, detection of overflow depends on the
291 behavior of some routines in the local C library, so it should be
292 regarded as unreliable. In any case, integer overflow and underflow
293 are generally not detected reliably for intermediate results. Float-
294 ing-point overflow and underflow are detected to the degree supported
295 by the hardware, which is generally pretty reliable.
296
297 Conversion among internal representations for integer, floating-point,
298 and string operands is done automatically as needed. For arithmetic
299 computations, integers are used until some floating-point number is
300 introduced, after which floating-point is used. For example,
301 expr 5 / 4
302 returns 1, while
303 expr 5 / 4.0
304 expr 5 / ( [string length "abcd"] + 0.0 )
305 both return 1.25. Floating-point values are always returned with a
306 ``.'' or an e so that they will not look like integer values. For
307 example,
308 expr 20.0/5.0
309 returns 4.0, not 4.
310
311 STRING OPERATIONS
312 String values may be used as operands of the comparison operators,
313 although the expression evaluator tries to do comparisons as integer or
314 floating-point when it can, except in the case of the eq and ne opera-
315 tors. If one of the operands of a comparison is a string and the other
316 has a numeric value, the numeric operand is converted back to a string
317 using the C sprintf format specifier %d for integers and %g for float-
318 ing-point values. For example, the commands
319 expr {"0x03" > "2"}
320 expr {"0y" < "0x12"}
321 both return 1. The first comparison is done using integer comparison,
322 and the second is done using string comparison after the second operand
323 is converted to the string 18. Because of Tcl's tendency to treat val-
324 ues as numbers whenever possible, it isn't generally a good idea to use
325 operators like == when you really want string comparison and the values
326 of the operands could be arbitrary; it's better in these cases to use
327 the eq or ne operators, or the string command instead.
328
329
330 PERFORMANCE CONSIDERATIONS
331 Enclose expressions in braces for the best speed and the smallest stor-
332 age requirements. This allows the Tcl bytecode compiler to generate
333 the best code.
334
335 As mentioned above, expressions are substituted twice: once by the Tcl
336 parser and once by the expr command. For example, the commands
337 set a 3
338 set b {$a + 2}
339 expr $b*4
340 return 11, not a multiple of 4. This is because the Tcl parser will
341 first substitute $a + 2 for the variable b, then the expr command will
342 evaluate the expression $a + 2*4.
343
344 Most expressions do not require a second round of substitutions.
345 Either they are enclosed in braces or, if not, their variable and com-
346 mand substitutions yield numbers or strings that don't themselves
347 require substitutions. However, because a few unbraced expressions
348 need two rounds of substitutions, the bytecode compiler must emit addi-
349 tional instructions to handle this situation. The most expensive code
350 is required for unbraced expressions that contain command substitu-
351 tions. These expressions must be implemented by generating new code
352 each time the expression is executed.
353
354 EXAMPLES
355 Define a procedure that computes an "interesting" mathematical func-
356 tion:
357 proc calc {x y} {
358 expr { ($x*$x - $y*$y) / exp($x*$x + $y*$y) }
359 }
360
361 Convert polar coordinates into cartesian coordinates:
362 # convert from ($radius,$angle)
363 set x [expr { $radius * cos($angle) }]
364 set y [expr { $radius * sin($angle) }]
365
366 Convert cartesian coordinates into polar coordinates:
367 # convert from ($x,$y)
368 set radius [expr { hypot($y, $x) }]
369 set angle [expr { atan2($y, $x) }]
370
371 Print a message describing the relationship of two string values to
372 each other:
373 puts "a and b are [expr {$a eq $b ? {equal} : {different}}]"
374
375 Set a variable to whether an environment variable is both defined at
376 all and also set to a true boolean value:
377 set isTrue [expr {
378 [info exists ::env(SOME_ENV_VAR)] &&
379 [string is true -strict $::env(SOME_ENV_VAR)]
380 }]
381
382 Generate a random integer in the range 0..99 inclusive:
383 set randNum [expr { int(100 * rand()) }]
384
385
386 SEE ALSO
387 array(n), for(n), if(n), string(n), Tcl(n), while(n)
388
389
390 KEYWORDS