15.1 Arithmetic Operators
As
in most computer languages, multiplication and division take
precedence
over addition and subtraction (in the absence of parentheses). So,
for example:
3 + 4 * 2 -- 11
3 * 4 + 2 -- 14
An operand that is a list
consisting of one number will be coerced to a number. An operand that
is a string, or a list consisting of one string, will be coerced to a
number if possible.
Syntax
number1 + number2
date + integer
Description
The
addition operator is not overloaded to perform string concatenation;
see on the ampersand operator (&) later in
this chapter. A date plus an integer yields
date increased by
integer seconds.
The result is an integer if the first operand is an integer and if
the second operand can be coerced to an integer without loss of
information. Otherwise, the result is a real.
- | subtraction; unary negation
|
Syntax
number1 - number2
date - integer
date - date-number
Description
A date minus an integer yields
date decreased by
integer seconds. A date minus a date
yields an integer, the number of seconds between them. For two
numbers, see on addition (+).
Unary negation has very high precedence.
Example
-3 ^ 2 -- 9
Syntax
number * number
Description
For the class of the result, see on addition (+).
Syntax
number1 / number2
Description
Both numbers are treated as reals, and the
result is a real.
Syntax
number1 div number2
Description
Both numbers are treated as reals; the first is divided by the
second, and the result is coerced to an integer by throwing away its
fractional part. Notice that this is not the
same as AppleScript's normal real-to-integer
coercion behavior.
Example
4 div 5 -- 0
(4 / 5) as integer -- 1
Syntax
number1 mod number1
Description
The first operand is divided by the
absolute value of the second and the remainder is returned. For the
class of the result, see on addition (+).
Syntax
number1 ^ number2
Description
Raises the first number to the power of the second. The result is a
real.
Do not blame AppleScript for the phenomena inherent in doing
floating-point arithmetic in any
language on any computer. It is the nature of computer numerics that
most values can only be approximated. Modern processors are
extraordinarily clever about compensating, but rounding operations
can easily expose the truth:
2.32 * 100.0 div 1 -- 231
Similarly, there may be situations where instead of comparing two
values for absolute equality you will do better to test whether the
difference between them lies within some acceptable small
epsilon.
|