Introduction

There is a disconnect between computing theory and algebra when it comes to interpretation of the unary minus operator.

- 2 ^ 2 = + 4
- 2 ^ 2 = - 4
Which is correct ?

The ambiguity arises because the short centered dash we call the minus sign is used for two purposes. The first is to identify a negative number as such. The second is to show a subtraction of one number from another. While evaluating terms in an algebraic expression several compilers seem not to obey the long established rules of algebra when choosing which meaning of a minus sign to employ. The subject is not new; Dr. Math addressed it in 1999. Chris Nebel suggests alt.algebra.help FAQ . It refers to an order of operations for chalkboard algebra at ops.

My hope is that the list of software will help readers to be careful. This page is doomed to remain an unfinished work. Contributions are welcome.



Defining the Problem

A term is a word used in mathematics to describe a part of an equation or expression that is separated from other terms by one of the binary operators, + and -. A sum of terms which involves variables and powers of them is called a polynomial.

A number, for this discussion, should be considered something obvious but we really will be talking about members of the field of real numbers and their approximate representation in digital computers. Mathematical details of groups and fields are relegated to an appendix.

A variable in algebra is a named quantity which is allowed to change. Usually a single letter from one of the many world-wide alphabets is used for the name. Convention calls for using early letters like a, b, c for variables which aren't expected to change much and x, y, z for unknowns or for computed values which relate to a curve on a graph. Algebraic variables are usually numbers but can also be vectors, matrices, and a lot more.

A variable in a programming language is a name which refers to an address in computer memory in which a number can be stored. Modern compilers make extensive use of abstractions to provide portability and reuse of code with the result that the correspondence between physical memory and pointers into it are obscured. Some programming environments insist that everything be treated as an object which must belong to a class. Operators may behave differently depending on the classes of their operands. The terms are not yet consistent between development systems. When a variable is treated as an object it may become an element in a container and special rules may apply. For this discussion, a computer variable is a number which is subject to change during processing and is stored in memory. It is typically assigned a name and software assigns physical memory for its storage.

A change from algebra is the common practice in the computing industry of allowing variables to be given multi-character names. A corollary of that is a requirement for an explicit multiplication operator. The * symbol needs now to be included between names to indicate multiplication. With some exceptions there is no longer an implied multiplication between two symbols placed one after the other.

Another change from algebraic notation is the absence of the vinculum which is a straight horizontal line above or below algebraic terms which indicates a collection inside of which operations are to be performed first. It is commonly seen in algebra texts as a horizontal fraction line separating a compound numerator from a compound denominator. It also appears as the extension of the square root symbol. A fraction displayed with a vinculum can have a minus sign directly to the left of the horizontal bar. Does the minus sign apply to the numerator, the denominator, or the fraction as a whole? Is it a unary minus? Does the decision depend on what appears to the left of the fraction? These are the areas where computer science seems to be off on its own when compared to algebraic conventions that predate computers.

In the absence of a chalkboard users of algebra are required to present equations as a line of text. Well established use of parentheses to replace the vinculum and employment of the solidus as a division operator have made the translation from algebra to compiler fairly painless, but problems remain. It is no longer possible to place an exponent above and to the right of an algebraic symbol. The in-line operators ** and ^ are used for exponentiation in a way that obscures the visual appearance of the exponent as a part of the symbol. In the past an exponent looked much like the atomic weight attached to a symbol for a chemical isotope. U235 for instance.


A moment please for a personal anecdote: I got into trouble performing some design calculations using Microsoft Excel. The task involved electrical power distribution for which the resistance of transformer windings and the overhead wires is a consideration. The energy lost in distribution is proportional to the square of the electrical current and the resistance of the wires. The resistances change with temperature and the current depends on usage by customers. Because several intermediate calculations used the negated square of the current as a common factor I placed the formula = - CURRENT^2 in a named cell. When small scale laboratory tests did not agree with my calculations I returned to the spreadsheet and discovered what I thought was a clear cut bug. Excel put a positive number in my named cell! No, the wires didn't overheat and sag into the tree line but exactly that did happen a few years ago in northern California. The catastophic failure affected lights in Colorado. I still wonder; did computer algebra have anything to do with that?


Another example from the real world comes from design of ducts for home heating. A circular cross section provides the largest area for a given amount of metal but other considerations dictate a rectangular structure. The maximum cross section then comes from a square. But just how much area is lost if the square becomes a rectangle while keeping the amount of metal constant?

Let L represent the side of the square. The area is L2.

Let X represent the amount removed from one side to be added to an adjacent side while keeping a constant perimeter. The area of the resulting rectangle is A = (L-X)(L+X).

The change in area is ΔA = (L-X)(L+X) - L2, which is an algebraic expression that is easily simplified to make life easier for the compiler. Why not?

ΔA = (L-X)(L+X) - L2 = L2 + LX - LX - X2 - L2 = - X2   right?

Not if your compiler interprets that leading minus sign as a unary operator. It doesn't know that all of the other terms in the original expression cancelled out and that minus sign is really a binary operator preceded by the zero that represents the terms you dropped. = 0 - X2 will usually compile correctly but one does wonder about the effects of optimization.


In the study of harmonic motion, radio transmitters, children's swings, and organ pipes, one regularly finds it necessary to evaluate the derivatives of sinusoidal motion with respect to time. Suppose:

f = frequency, t = time
ω = 2 π f    (the angular frequency in radians per second)
V(t) = sin(ωt)   (the amplitude as a function of time, t)
V'(t) = ω cos(ωt)   (the time derivative of the amplitude)
V''(t) = -ω2sin(ωt)   (the second derivative of the amplitude)

This formula is often equated to a forcing function in accordance with Newton's second law, F = mA, where the acceleration, A, is the second derivative with respect to time. The minus in front is not a unary minus attached to the ω. It is the result of differentiation of the cosine to get a negative sine (without a pun).


These expressions are all equal in conventional algebra but are different in an environment in which the unary minus is given a higher precedence than exponentiation.

x = - a2- b2
y = - b2- a2
z = - ( a2+ b2 )

In fact, the only condition under which they are all the same is if a = b = 0. Rearranging terms in a polynomial is common on a chalkboard.


There are compiler changes that would restore chalkboard algebra. One is simply to make exponentiation bind more tightly than the unary operators. Another is to make compilers more intelligent in the analysis of programmer meaning in expressions. Yet another is to make unary operators apply only to literal numbers and never to variables in memory. It's also possible to do away with unary operators altogether. The C compiler avoids the problem by not having an exponentiation operator. The line of code:

ΔA = - pow(x, 2);

doesn't invoke the unary option. Why not? It's as much a leading minus as the one in - x2. Isn't x2 a function of x? Perhaps the precedence rules for a function would be more appropriate.

The solution for engineers seems to be inclusion of lots of parentheses for prophylaxis. Another option is to know which software is safe and which is not. To that end we have looked at available software. It is a bit difficult to come up with politically correct labels for the programs. It isn't that the unary minus folks are wrong. It's just that some software is oriented toward engineering and some uses more liberal interpretations allowed by computer science. Sentient people can and will continue to insist that -X2 is logically positive at least for real values of X. The problematic software is mostly accurate in the fine print of its documentation and can be identified by careful reading of a manual. Engineers, though, are not likely to anticipate changes to their previous experience or to search for "precedence" in a help file.


Rebuttal

This space left for text to be provided by a willing computer scientist with another opinion.


Summary and Index

We'll use these codes to describe the software:

Type Name Rate Comment
Calculators
bcCAUT*NIX
dcMOOT*NIX
MathPadSAFEMac OS
Graphing CalculatorSAFEMac OS classic, Windows
CalculatorMOOTMac OS X
CalcServiceCAUTMac OS X
GoogleCAUTWWW
Magic Number MachineSAFEMac OS X
AssemblersGoMOOT
Compilers
FORTRANSAFE
ALGOLX
COBOLCAUT
PL / ISAFE
CMOOT
ADASAFE
AWKSAFE
SmallTalkX
Common LispMOOT
PythonSAFE
APLMOOT
PascalSAFEExtended Pascal
DylanXMac OS
Real BasicMOOT
Visual BasicXMicrosoft
GW-BASICSAFEBASIC for the Kaypro
GW-BASICSAFEEarly Microsoft BASIC
Chipmunk BasicCAUTMac OS
SASSAFEMainframe and others
Scripting
perlSAFE
perl 6SAFEperl 6 coming soon
VBASAFEMS Visual Basic for Applications
VBSCAUTMicrosoft Visual Basic Scripting
HypercardCAUTMac OS classic
ApplescriptCAUTMac OS
SmileLabCAUTMac OS X
Igor ProSAFEMac OS, Windows
Symbolic Math
MapleSAFEWaterloo
MathematicaSAFEWolfram Research
Spreadsheets
AppleWorksSAFEMac OS
MS ExcelCAUTVersion 4
MS ExcelCAUTVersion 2001
Open Office ExcelCAUT
Gnumeric 1.0.12SAFE*NIX
Gnumeric 1.1.17CAUT*NIX
VisicalcMOOTEarly Apple OS
SupercalcXEarly CP/M
MS WorksSAFEMac and PC
MiniCADSAFEMac and PC, Now Vectorworks
Lotus 1-2-3SAFEMostly PC
Under Consideration
CLISTCAUTMainframe
REXXCAUTMainframe
Easytrieve PlusMOOTMainframe
GAUSSXBy Aptech

Calculators


Texas Instrument Calculators MOOT Index

"TI" style pocket calculators simply will not allow entry of a minus sign in front of a variable or number. Rather they have two buttons, a binary subtraction operator and a change sign operator. It is impossible to enter a formula that starts with a minus.


RPN (Hewlett Packard) Calculators MOOT Index

RPN calculators avoid the problem altogether by forcing one to ENTER or operate on things based on a stack. FORTH and Postscript are similar in the language world.


UNIX bc CAUT Index

set a = 2
set b = -a^2   Returns + 4


UNIX dc MOOT Index

This calculator uses stack oriented reverse Polish procedures which do not allow entry of anything like -22. One must push a 2, square it, and then change the sign. There is no ambiguity.


Mac OS classic calculator MOOT Index

Does not have a power function.


MathPad calculator for Mac OS SAFE Index

MathPad is a calculator for the Macintosh which accepts algebraic formulas. It treats -x^2 as an engineer would returning -4 when the variable x has been set to either plus or minus 2.


Pacific Tech graphing calculator SAFE Index

Under Mac OS 9.1 the Graphing Calculator version 1.3, when presented with:

y = -x^2

draws a nice parabola, negative everywhere, which looks like an inverted coffee cup.

MacGraph from Pacific Tech is now shipping for Mac and WinTel.


Mac OS X calculator MOOT Index

This calculator operates in "TI" mode and can take the square of an entered number. After that one can change the sign but there is no procedure for entering a formula like -X^2. There is a tantalizing yx button in advanced mode which allows changing the sign of either of the inputs but negating the result is only possible after the action is taken. It's also not exactly clear what "y" is. There is no stack.

In advanced mode, if you enter a minus sign and then a five - follow that by pressing the yx button - and then entering a 2 - and then an = sign. The result is -25, the chalkboard algebra solution. If you press the minus sign - follow with a 5 - and then press the x2 button you see + 25. If you then poke the = sign it changes to -25. I remain confused.


CalcService 3.1 CAUT Index

This calculator operates as a service in Mac OS X. It is by DEVON technologies You enter a formula in any cooperating text editor and use either a menu item or a key combination to evaluate the formula that is selected as text. Results are returned to the document being edited or into a secondary window. I ran these three lines by typing up to, but not including, the = signs. CalcService placed the = signs and the results directly into this document.

a=3; b=4; -a^2-b^2 = -7
a=3; b=4; -b^2-a^2 = 7
a=3; b=4; -(b^2+a^2) = -25

The caution rating is because of the interpretation of the leading minus signs in the first two lines. With prophylactic parentheses the service works fine.


Google Calculator CAUT Index

As a part of its search system Google now alows a formula to be entered. It tries but doesn't understand chalkboard algebra and applies a leading minus to a variable before procesing an exponent. The result, after you poke the search button, does add parentheses to the formula you entered so that it is clear just how it was interpreted. So long as you read the whole result you are unlikely to cause a power failure.


Magic Number Machine SAFE Index

Magic Number Machine (v1.0.3) by Matt Gallagher is freeware for MacOS 10.2 or better. Source code requires 10.3. It handles complex numbers and matrices in addition to being a typical calculator. The keystroke sequence "-", "5", "x^2", "=" produces "-52 = -25" which is the safe answer. But there is also a "+/-" key used for changing the sign of a number. That is indeed the unary plus or minus operator and the sequence "5", "+/-", "x^2", "=" generates "-52 = 25". There is some danger in that no feedback about the interpretation is provided but it only occurs when the operator has specifically asked for the unary minus operator. Amusingly, the sequence "-", "5", "+/-", "x^2", "=" results in "- -52 = -25" proving that the unary +/- operator applies only to the digit at the right end of the edit string as it is applied.


Assemblers


Assemblers MOOT Index

Very few, if any, assemblers even support a power function and if they do it's a power of a number loaded into a register where it already has its sign established. It is possible that some assemblers for digital signal processors have exponentiation options. Note that earlier assembly commands seldom had an ENTER instruction. One either did a CLEAR_AND_ADD or a CLEAR_AND_SUBTRACT into a register to place a positive or negative number.

For completeness FORTH and Postscript are not really assemblers but they are similar in that they use postfix notation in the manner of a reverse Polish calculator.


Compilers


FORTRAN SAFE Index

The oldest is FORTRAN which abides by the rules of algebra as used by scientists and engineers. Computer Programming, Fortran IV (1966) has this to say:

The order of calculation will be according to the hierarchy

Operation Description
** Highest (evaluated first)
- Evaluation of unary minus quantities (9)
* / Multiplication and division
+ - Addition and subtraction

McCracken's book on FORTRAN 66 doesn't discuss the matter.

The FORTRAN 77 Reference Manual from Data General, (1981) has this to say:

F77 evaluates arithmetic expressions in order, by the precedence of each operator, as follows:

Operation Description
** Highest (evaluated first)
* /
+ - (unary)
+ - Lowest (evaluated last)

Note that the unary operators have moved down a notch from FORTRAN IV.


ALGOL X Index

Perhaps the next is ALGOL but the only book I have is silent.


COBOL CAUT Index

Dennis M. Stowell of Wells Fargo Bank kindly tested a current version of Cobol with these results:

The compiler used was IBM's COBOL for MVS and VM, release 1.2.1 (AKA LE COBOL or ANSI standard 1985 COBOL). There is a 1995 ANSI standard COBOL but that has managed, somehow, to incorporate object oriented syntax into the prior standard and nobody I know of is using it yet.

The COBOL COMPUTE statement has the following form:

COMPUTE Y = F(X) END-COMPUTE.
COBOL -3**2 = +9

A shortened list of the precedence rules from IBM's manual (1993) is:

Operation Description
Unary + or - Highest precedence operator
** Exponentiation
/ or * Division or multiplication
Binary + or - Addition or subtraction

PL / I SAFE Index

In "PL/I Programming"(1973) the order of operations is specified in a series of rules:

Rule 1. The order in which arithmetic operations are performed is:
1. Exponentiation (raising a number to a power moving from right to left in an expression.)
2. Multiplication or division (whichever appears first moving from left to right in an expression.)
3. Addition or subtraction (whichever appears first, moving from left to right in an expression.)

Rule 2. Parentheses are used. (in the usual way.)

Rule 3. A prefix operator is an operator that precedes, and is associated with, a single operand. The prefix operators are; NOT, + Positive sign, - Negative sign. Prefix operators are contrasted with infix operators which specify a specific operation such as addition, subtraction, multiplication, etc.

Rule 4. Any expression or element may be raised to a power and the power may have either a positive or negative value. The exponent itself may be an expression.

Rule 5. If two or more operations of the highest priority appear in the same expression, the order of priority of those operators is from right to left. For example, prefix operations are performed on the same level as exponentiation. In the expression -A**2 the order of operations is 1: exponentiation and 2: prefix operation, negation.

The emphasis in rule 3 is this author's. This treatment is a particularly conscientious description of algebra as it was known before computers. Note the distinction that a "prefix" operator, the one we now speak of as unary, must be "associated with" an operand. The algebraic sign of a term in a polynomial does not appear to meet that requirement. Note that the specific example in rule 5 directly relates to the problem at hand. It results in a negative evaluation of -A2.


C MOOT Index

The C compiler, excluding versions A and B, dates to 1973 or so but, since it doesn't support a power operator at all. it's definitions are moot.

Although IBM can hardly be considered the authority on C, one of their manuals (1987) has this to say:

"The three binary operators *, /, and %, and the unary operator: -, are multiplicative operators. They all require operands that have arithmetic data types.

Multiplication by -1 is expressed:
  - expression
The same rules as for multiplication apply. That is:
  - expression == -1 * expression.

There is room for interpretation. In a statement like y = -x2 Is the expression x2 or is it just the x? Making the unary minus a multiplication rather than a subtraction from zero seems to introduce an ambiguity. Of course C doesn't have an exponentiation operator so the point is moot.

Emmanuel from Satimage reports on the AppleScript mailing list:

There is no exponentiation in C, but the unitary "-" (and the unitary "+" as well) have a high precedence level: they are two levels above "*" and "/".


ADA SAFE Index

The Ada 95 Hypertext Reference Manual offers;

4.5 Operators and Expression Evaluation

The language defines the following six categories of operators (given in order of increasing precedence). The corresponding operator symbols, and only those, can be used as designators in declarations of functions for user-defined operators.

Operation Description
**   abs   not highest precedence operator
*   /   mod   rem multiplying operator
+   - unary adding operator
+   -   & binary adding operator
=   /=   <   <=   >   >= relational operator
and   or   xor logical operator

The Ada '83 Language Reference Manual is similar.


AWK SAFE Index

GNU AWK has this to say: The $ sign in AWK is a reference to a value in a data field specified by number.

The precedence of prefix unary operators does not matter as long as only unary operators are involved, because there is only one way to interpret them: innermost first. Thus, $++i means $(++i) and ++$x means ++($x). However, when another operator follows the operand, then the precedence of the unary operators can matter. $x^2 means ($x)^2, but -x^2 means -(x^2), because - has lower precedence than ^, whereas $ has higher precedence.

A table follows which simply places the unary minus and plus lower than exponentiation. Thus the SAFE rating.


SmallTalk X Index

Smalltalk supports ** as a power operator. Awaiting precedence information.


Common Lisp MOOT Index

The exponentiation operator is expt. Lisp uses parentheses to pass arguments, in prefix notation, to subroutines and everything is done that way.

(expt x y)

Will return xy and you're on your own to change the sign or not.


Python SAFE Index

This exchange took place in April 2003.

The current operator precedence places unary plus and minus higher than exponentiation. This leads the counter intuitive result:

>>> -2.0**2.0
-4.0

Is there a good reason for the Python order of precedence?

The answer by Gregory Warnes was this:

I would say that the behavior is what I expect. I would never expect -2.0**2.0 to mean (-2.0)**2.0. Nobody I've met in a mathematical context (engineers and mathematicians) have ever assumed your interpretation.
Where have you seen that interpretation?

Deivy Petrescu <applescript@dicas.com> reports:  "you can include python in the ones that use -2^2=-4."

I think we can give Python a chalkboard algebra SAFE rating.


APL MOOT Index

" Pathologically aberrant languages just confuse the heck out of things. As we mentioned before, APL works right to left, and all operators have the same precedence. "

APL does not have precedence rules like algebra. It relies on the right to left sequence and levels of parentheses ( ) to establish the order of execution. We give it an MOOT rating because parentheses are required for almost everything, but the right to left rule does evaluate the exponent in -x^2 before the negation is applied.


Pascal SAFE Index

Early versions of Pascal did not support exponentiation with an operator. An Extended Pascal specification, (as PDF) (as text), about 1990, introduced the ** and pow operators. POW raises a value to an integer power, and ** accepts a real exponent.

More recent documents have appeared, An introduction by Tony Hetherington is popular. The free software folks are active with Welcome and a discussion of Pascal operators which is germane. From there:

The following table lists all built-in GNU Pascal operators, ordered by precedence:

Operation Description
not   &   @ Highest (evaluated first)
pow   **   >< Exponentiation
*  /  div mod and shl shr xor *<  /<  *>  /> Multiplication and division
+  -  or  +<  -<  +>  -> Addition and other stuff
<  =  >  in  <>  >=  <= Lowest (evaluated last)

Note that the unary minus is not explicitly mentioned. That leaves the actual interpretation to the implementer of each compiler. Almost surely the specification intends that there shall be no unary minus and that a leading minus sign should be interpreted as (-1)* but testing of each compiler is in order. The SAFE rating is conditional. Someone is likely to conclude that the not operator is equivalent to the missing unary minus.


Dylan X Index

Once proposed for the Macintosh. No information yet


Real Basic MOOT Index

Real Basic does not support an exponentiation operator. It uses the Pow(variable, exponent) function exactly as employed in C.


Microsoft Visual Basic SAFE Index

Visual-Basic shows an operator precedence table for Visual Basic which places exponentiation in front of negation. That is consistent with chalkboard algebra. The link does not explicitly discuss the case of -x^2 so the conclusion must remain in question until tested in vivo. There are too many versions of Microsoft BASIC with divers rules.


GW-BASIC for the Kaypro SAFE Index

The "Microsoft GW-BASIC Interpreter Manual" (1984) lists this order of operations:

Operation Description
^ Exponentiation
- Negation
*,/ Multiplication and division
\ Integer division
MOD Modulus arithmetic
+, - Addition and subtraction
<,>,etc Relational operators
NOT
AND Bit by bit AND
OR, XOR Bit by bit
EQV
IMP

Negation we take to be what is now called the unary minus operator. Note that exponentiation binds more tightly and adheres to algebraic conventions.


Microsoft GW-BASIC SAFE Index

The "Microsoft GW-BASIC Interpreter" user manual (1986) lists the order of operations:

Operation Description
^ Exponentiation
- Negation
* Multiplication
/ Floating Point Division
+ Addition
- Subtraction

Negation we take to be what is now called the unary minus operator. Note that exponentiation binds more tightly and adheres to algebraic conventions.


Chipmunk Basic CAUT Index

Chipmunk BASIC disagrees with chalkboard algebra though it may be the only BASIC to be that way. I tried this:

Chipmunk BASIC v3.5.8b7
>dim x
>dim y
>let x = 2
>let y = -x^2
>print y
4   (Consistent with applying the minus and then squaring.)
>

The documentation clearly gives a higher operator precedence to the unary minus.

Operation Description
( ) Parentheses override everything
- unary_minus
functions( )
^ Exponentiation
* / mod
+ -
= < > <= >= <>
not
and
or xor Lowest precedence

Notice the inclusion of functions( ) immediately below the unary minus. I tried evaluating - exp(x) with x set to unity. The result was -e and not 1/e so the position of unary minus in front of function( ) doesn't mean the unary minus gets applied to the function argument before the subroutine call. It probably means only that something like cos(x)^2 is evaluated as cos2x rather than cos(x2). It does bring to mind that xn is a valid function of x in chalkboard algebra. Perhaps if the syntax x^n were interpreted as shorthand for an inline function equivalent to pow(x, n) the disconnect between computer science and algebra would disappear.


SAS SAFE Index

SAS has a long history as an integrated data processing language for use on Mainframes, UNIX, and Windows. It supports exponentiation and unary operators. The unary minus and the exponentiation operator, **, are assigned to the highest priority group but, because that group is evaluated right to left, the ** in -2**2 will be evaluated before the change of sign. The company also supports the Macintosh with JMP and StatView software.

The order of precedence is shown in a private website from which I have extracted the arithmetic operators:

Priority Order of Evaluation Symbol Definition
Group I right to left ** exponentiation


+ positive prefix


- negative prefix
Group II left to right * multiplication


/ division
Group III left to right + addition


- subtraction

Scripting


MS Visual Basic for Applications (VBA) SAFE Index

Seems to conform to chalkboard algebra in spite of its use as the programming language for Excel. Consider this macro:

Sub power( )
 Dim arg1 As Double
 Dim arg2 As Double
 arg1 = Range("A1").Value ' The variable
 arg2 = Range("A2").Value ' The exponent
 Range("A3").Value = -arg1 ^ arg2
End Sub

The last line places the result corresponding to =-A1^A2 into cell A3 and produces the expected negative result. Note that a user defined function in VBA will not be treated as a unary minus condition as it is executed from its containing cell.


Microsoft Visual Basic Scripting CAUT Index

VBScript is different from VBA (for applications) and is intended for scripting web-like things. Its operator preference is clearly shown in the link with negation preceeding exponentiation - the computer science way. I am unable to test the product to see if it's really true.


Hypercard CAUT Index

Goodman's Hypertalk book (1987) says this:

Operation Description
( ) Operators within parentheses are performed first
Minus sign (for a negative number) and boolean not
^ (to the power)
* / div mod
+ -
& && (concatenate)
> < <= >= (contains, is in)
= < > !=
and
or

Notice that the unary minus has moved forward in the hierarchy as of Hypercard in 1987 or so. That is likely the heritage of AppleScript but it's not so clear what the term "for a negative number" means. Does it include a variable or a named container?


AppleScript CAUT Index

set avalue to 2
set thesquare to - avalue ^ 2
thesquare
--> + 4

The official information for AppleScript is at Operator Precedence Apple will not correct it because "it might break existing code." There is an amusing blog on the subject in which a very disappointed user notes the unary minus disconnect and other things.


SmileLab CAUT Index

SmileLab uses Apple's Open Scripting Architecture which is an alternative to AppleScript's own environment. The software is still under development but it is available from Satimage Software. You will need to install Smile itself under Mac OS X. A wide range of scientific tools with matrix manipulation and graphing directly into Adobe PDF format is accessible using the syntax of AppleScript. I tried:

set n to 33
set x to creatematrix "x" ncols n nrows 1 -- fills columns with consecutive integers
set x to addlist x with -16 -- converts to zero centered list
set x to divlist x with 4 -- sets a scale factor
set y to evalformula "-q^2" with {q:x} -- plotted cup always positive
set y to evalformula "0-q^2" with {q:x} -- plotted cup always negative

Each curve was plotted separately using some more Applescript which I do not include here. The treatment of the unary minus is, naturally, compatible with the underlying AppleScript and gets the same CAUT rating.


perl SAFE Index

The Camel Book with Larry Wall as first author (2000) is very clear and implies that other software isn't always the same.

Exponentiation

Binary ** is the exponentiation operator. Note that it binds even more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. The operator is implemented with C's pow(3) function. . .


perl 6 SAFE Index

Perl 6 is a major revision to perl which is being worked on by volunteers. Parrot is a virtual machine intended to support perl and possibly other scripting languages. No changes are expected in the unary minus area.


Igor Pro SAFE Index

Igor Pro by Wavemetrics is interactive software for experimentation with scientific and engineering data. This test by Reinhold Penner.

print -3.1415^2
--> -9.869.


Symbolic Math


Maple SAFE Index

Maple is a symbolic algebra program from Waterloo, Canada. It is capable of solving algebraic equations and returning answers in literal form.

The reference manual declares the presence of a unary minus operator but remains silent on its position in the precedence table. The binary subtraction operator is clearly below exponentiation. There is however another introductory manual (1992) by Bruce Char and 5 others. It is "First Leaves". As an example of common beginner's problems, it says:

Negative has a lower precedence than exponentiation.
> -5^2 returns -25.

The > character is the command line prompt for Maple.


Mathematica SAFE Index

Mathematica is a well known symbolic algebra package by Wolfram Research. A visit to www.mathworld.wolfram.com brought me to the page mathmlcentral where I could experiment. MathML is a mathematical markup language which allows for entry of formulas in pencil and paper algebraic notation. I entered the formula -x^2 as text and asked that it be converted to markup language. The result was:

<math xmlns='http://www.w3.org/1998/Math/MathML'>
 <mrow>
  <mo>-</mo>
  <msup>
   <mi>x</mi>
   <mn>2</mn>
  </msup>
 </mrow>
</math>

Another option was to make a plot. I chose a range from -3 to +3 and got a parabola wholly in the negative half of the X-Y plane consistent with squaring x before applying the minus sign.


Spreadsheets:


AppleWorks 6 SAFE Index
A B C
1 2.0 2 numeric entry
2 = - A1^2 -4 return is negative

Microsoft Excel 4 CAUT Index
A B C
1 2.0 2 numeric entry
2 = - A1^2 4 return is positive
3 = - A1^2 / 4 1 return is positive
4 = - + A1^2 4 return is +4 without error message

Microsoft acknowledges the disconnect with chalkboard algebra for all versions of Excel calling it an "unexpected positive value" but argues that the result is correct because of their order of operations. The suggested workaround is to use prophylactic parentheses.


Microsoft Excel 2001 CAUT Index
A B C
1 2.0 2 numeric entry
2 = - A1^2 4 return is positive
3 =2 2  
4 =5 5  
5 = - A3^2 / (-A3^2-A4^2) - A4^2 / (-A3^2-A4^2) 1 return is positive
6 =( - A4^2 - A3^2) / (- A3^2 - A4^2) - 1 return is negative

The behavior is the same as Excel 4 but note that macros and user defined functions written in VBA work the opposite way. A user defined function avoids the unary minus interpretation just as, say, = - SQRT(A1) would.

In the help documentation for Excel 2001 one finds, for the error function add-in, this definition:

But what is that -t2? The kernel of the integral is exp(-t^2) and the reader is invited to make a plot of that. You will create a curve,which has value 1 at t = 0 and increases exponentially at each side. It's a far cry from the infamous Bell Curve that is the correct Gaussian form for the error function. One needs to call out exp(0-t^2) or exp (-(t^2)) in Excel.


Open Office Excel CAUT Index

Testing www.openoffice.org as run on Knoppix Linux. Treatment of unary minus is identical to that of MS Excel. One could assume it was done to avoid breaking existing spreadsheets, but Open Office does repair the date system for dates prior to the non-existent 29 Feb. 1900.


Gnumeric 1.0.12 SAFE Index

Performs scientifically, = - 2^2 evaluates to - 4 whether the variable is numeric or a cell reference. Tested on Red Hat Linux.


Gnumeric 1.1.17 CAUT Index

Performs in computer science mode, = - 2^2 evaluates to + 4. Tested on Knoppix. It's interesting that this is the newer version number. The Gnumeric home page indicates a need for compatibility with Microsoft Excel.

The gnumeric group is aware of the inconsistency and is bothered by the necessity to compile from cell contents using yacc technology in which the precedence table has to be set up at compilation time of gnumeric itself. Version 1.1.20 will automatically add parentheses to typed entries so that = -2^2 will immediately be changed to = (-2)*2. That will effectively warn a less than cautious engineer. Version 1.3 will include a preference item for compatibility with algebra or with Excel.


Visicalc MOOT Index

Visicalc operated on a strict left to right basis just like an assembler. Severe memory limitations probably prohibited even the rudimentary formula translations of FORTRAN. There is no danger but parentheses are required for almost everything.

There is actually a version of Visicalc still available for use on a machine which will run MS-DOS.


Supercalc X Index

Can't remember. It's a CP/M product. Probably OK but of historical interest only.


Microsoft Works SAFE Index

Microsoft Works version 7.0 spreadsheets run on an Intel box running Windows XP behave in chalkboard algebra style. It is amusing that the convention is completely different than Microsoft Excel.

A historical perspective would be interesting. Were previous versions of Works the same?


Graphsoft MiniCAD-7 SAFE Index

The worksheets in MiniCAD operate according to algebraic conventions. -2^2 evaluates to -4.


Lotus 1-2-3 SAFE Index
A B C
1 2.0 2 numeric entry
2 -A1^2 -4 return is negative

Lotus 1-2-3 for Macintosh version 1.0 of 1991 operates scientifically when tested on a Macintosh IIFX running system 7.5.3. -2^2 evaluates to -4. Notice how the leading minus also introduces a formula as opposed to a value.


References

(1966) "Computer Programming, Fortran IV", Decima M. Anderson, Drexel Institute of Technology, Prentiss Hall, 1966, ISBN 0-13-164822-5. Return

(1973) "PL/I Programming", Joan K. Hughes, John Wiley & Sons, Inc., 1973, ISBN 0-471-42032-8. page 51. Return

(1981) "Fortran 77", Data General Corporation, 1981, ISBN 0-13-164822-5. Return

(1984) "Microsoft GW-BASIC Interpreter Manual, Version 3.1", Microsoft Corporation, 1984, Document number 8112-310-00, page 3-9 Return

(1986) "Microsoft GW-BASIC Interpreter, User's Guide and User's Reference", Microsoft Corporation, 1986, Document number 410130001-330-R02-0787, p 56. Return

(1987) "The Complete Hypercard Handbook", Danny Goodman, Bantam Books, 1987, ISBN 0-553-34391-2, p 575. Return

(1987) "C Language Reference" IBM System/88 SC34-0746-2, Third edition March 1987", Published by IBM with no ISBN identification., page 4-7. Return

(1992) "First Leaves, a tutorial introduction to Maple V", Bruce W. Char et al., Waterloo Maple Publishing and Springer Verlag,, 1992, ISBN 0-387-97621-3, page 8. Return

(2000) "Programming Perl, Third Edition", Larry Wall, Tom Christiansen, & Jon Orwant, O'Reilly, 2000, ISBN 0-596-0027-8., page 92. Return

(1993) "VS COBOL II, Application Programming Guide for MVS and CMS, Release 4, Sixth Edition, March 1993, IBM publication number SC26-4045-05 Return


Appendix

Information has been raised in various discussions but is not critical for understanding.


The mathematical basis of algebra starts with group theory. A group is a set of objects, numbers for us, over which a binary operator is defined. The operators + and * come to mind but neither is required. To be a group there are four axioms that must be satisfied for the operation:

For many groups an additional axiom, commutivity, requires that

Such groups are called Abelian. Ordinary multiplication and addition operators are Abelian. Matrix multiplication, as used for rotations in three dimensional graphics, is not.

Ordinary numbers have at least two common operations defined. They are addition and multiplication. Subtraction and division are specifically not included. Rather they are treated in terms of addition of and multiplication by the required inverse objects. With two operations defined, each of which obeys the group axioms, the group becomes a field. One additional axiom is required, distributivity, which determines an order of priority of one operation over the other. The requirement for an inverse is relaxed for one of the operations in the case of the null element for the other. There is no multiplicative inverse of zero. Multiplication is distributive over addition:

Note that the signed integers do not form a field. There is no inverse under multiplication. The rational numbers, expressible as a ratio of two integers do form a field. The irrational numbers and the transcentental numbers also form fields and we don't need to talk about the difference here. In computer languages we have a defined type real which is similar to a mathematical transcentental number but is not close enough to form a true field. The problem is that no computer can supply an infinite number of bits to store both a number and its exact recriprocal. Even in common decimal notation most real numbers can be represented only as repeating decimals; 1/3 = 0.3333... forever. Put another way there are only 264 possible combinations of 64 bits in an IEEE float while there are an infinity of real numbers. Note that the term real in mathematics implies that the number has no imaginary part. It does not involve sqrt(-1). Computer science has adopted the term to describe a floating point variable.

So long as we are using real numbers, either the computer type or the mathematical type, with two operators the field axioms are sufficient to define an algebra complete with precedence rules. There are only multiplication and addition. Division by A is accomplished by multiplying by A-1 and subtraction is accomplished by adding (-A) where that minus sign is the unary minus operator.

The exponentiation operator is not defined in a field. Rather the power operation is treated as a function of a variable. It might be possible to define a super field with three operators but mathematicians have never done so. They think of exponentiation as a function much like the pow() function in C.


There has been discussion of formulas like: y = -x ^-n where it is agreed that the negation of the n is a unary minus but there is no agreement that the formula should evaluate to y = (-x)^(-n) rather than - (x^(-n)). An expression like y = x^-n+2 obviously requires parentheses if the exponent is intended to be (-n+2).


The unary minus can be replaced in an algebraic expression by an implied multiplication by (-1) or by an implied subtraction from zero. The effects are the same because in both cases the formula translator is tricked into treating the operator as binary. The multiplicative option has an academic problem in that it requires a unary minus to create the (-1) item which leads to a circular reference. In the group of real numbers under addition the required inverse element, A', is defined by A + A' = 0. The inverse of A added to A must produce null. It's a pretty short leap to move A to the other side resulting in A' = 0 - A even though that binary minus is not a part of the group definition. Of course such binomials as (0 - A) must be parenthesized to take account of the distributive axiom when multiplication is added to the group to create a field.


Spaces or other white space in formulas have been used to represent a multiplication (Mathematica) but never to distinguish a unary minus from a binary operator. In chalkboard algebra xy means x * y. When words instead of characters are used exxwye is not clearly exx * wye but exx wye can be read by a compiler to mean multiplication by juxtaposition..


PEMDAS has been mentioned as an mnemonic for "parentheses, exponentiation, multiply/divide, add/subtract". I never got that in school but it is pretty much correct. It does not admit to the existence of a unary minus.


It has been pointed out that "computer science" does not demand that the precedence of the unary minus be elevated. Correct. In fact with automated compiler generators like yacc the precedence table is presented as data to the compiler compiler. I do not mean to deprecate computer science as a field. Without it most of the applications here would not exist. But it is computer science which has made it possible for the disconnect to occur.


The ** grapheme was chosen for exponentiation during the development of Fortran at a time when a byte was six bits and there were no lower case letters. Character encodings were later extended to the 7 bits of ASCII giving us the ^ character which seems more appropriate as an exponent. But the C language picked it up as the bitwise exclusive or operator. Amusingly, the expression -2^2 in C evaluates to -4, but it's only an accident of twos complement arithmetic. -2 = 1111 1110 as a signed char after applying the unary minus first. The exponent is +2 = 0000 0010. The exclusive or is 1111 1100 = -4, the SAFE answer!


There was some discussion of a failure of a mission to Mars caused by a compiler problem. It was in fact a conversion between metric and imperial units that was the error and not misinterpretation of a unary minus. Someday I would like to see an object-oriented class called "measure". In it would be numbers with their physical units included as a property. There would also be an estimate of error. Operators would be overloaded as required so that one could multiply kilograms by height and end up with joules without a lot of mental effort. An automatic type conversion would take care of the required acceleration due to gravity complete with error analysis. But that is indeed another subject.


Contacting the Author

Douglas P. McNutt
The MacNauchtan Laboratory
7255 Suntide Place
Colorado Springs, CO 80919-1060
voice 719 593 8192
dmcnutt@macnauchtan.com
http://www.macnauchtan.com/
ftp://ftp.macnauchtan.com/


Change Log

07/11/03Added SAS
07/11/03Changed gnumeric
07/12/03Added CalcService 3.1
07/13/03Spelling and grammar
08/31/03Mac OS X calculator expanded
08/31/03Visicalc
08/31/03x^y operations in Mac OS Xcalculator expanded
08/31/03MS Works 7.0 found safe
08/31/03Google calculator added
12/03/03Magic Number Machine added. Perl 6 changed. Noted request to include Mariner spreadsheet.
03/24/06Table formatting changed to handle new css conventions.
Copy and execute
date -n "+%D"Copy and execute