7 ms·
An annoyance with spreadsheets that deterred me from ever using them in teaching is that they've perpetuated a arithmetic order-of-precedence bug. ("Bug" in the
by bikenaga 2y ago
An annoyance with spreadsheets that deterred me from ever using them in teaching is that they've perpetuated a arithmetic order-of-precedence bug. ("Bug" in the sense that it contradicts long-standing mathematical convention.) If you type
-3^2
in a cell and press ENTER, the spreadsheet tell you it's "9". It should be "-9"; in math, exponentiation has precedence over unary minus, so you square 3, then negate the result. For instance, if you tell students to graph "y = -x^2", they should draw a parabola opening downward.
I don't have a recent copy of Excel to check this in, but this was the case in the '97 version. I just tried it in the current LibreOffice calc, and it returns "9". My guess is that one of the early spreadsheets messed up the order of precedence, and everybody after copied it for compatibility.
On the other hand, I just tried maxima and python and they both give "-9".
I wonder if this particular problem afflicts people who copy formulas from (say) math books into spreadsheets.
- mobilio 2y agoBut it's 9! Check it: https://www.mathplanet.com/education/pre-algebra/explore-and-understand-integers/multiplying-and-dividing-with-integers#:~:text=You%20also%20have%20to%20pay,the%20product%20is%20always%20positive https://www.mathplanet.com/education/pre-algebra/explore-and.... "You also have to pay attention to the signs when you multiply and divide. There are two simple rules to remember: When you multiply a negative number by a positive number then the product is always negative. When you multiply two negative numbers or two positive numbers then the product is always positive." So basically you have -3x-3 and result is 9.
- n_plus_1_acc 2y agoCorrect, but irrelevant to the question. The usual rules of math require it to be parsed like -(3²), so there are only positive numbers being multiplied.
- shagie 2y agohttps://www.wolframalpha.com/input?i=-3%5E2 https://www.wolframalpha.com/input?i=-3%5E2 https://en.wikipedia.org/wiki/Order_of_operations https://en.wikipedia.org/wiki/Order_of_operations Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction -3^2 would then be correctly parsed as -(3^2) which is -9. Parsing it as (-3)^2 would require the addition of parentheses. This gets to the special case of the unary minus sign... which the Wikipedia article specifically calls out. Special cases Unary minus sign There are differing conventions concerning the unary operation '−' (usually pronounced "minus"). In written or printed mathematics, the expression −3² is interpreted to mean −(3²) = −9. In some applications and programming languages, notably Microsoft Excel, PlanMaker (and other spreadsheet applications) and the programming language bc, unary operations have a higher priority than binary operations, that is, the unary minus has higher precedence than exponentiation, so in those languages −3² will be interpreted as (−3)² = 9. This does not apply to the binary minus operation '−'; for example in Microsoft Excel while the formulas =-2^2, =-(2)^2 and =0+-2^2 return 4, the formulas =0-2^2 and =-(2^2) return −4. (edit) Digging into this a little bit more... https://www.gnu.org/software/bc/manual/html_mono/bc.html#TOC13 https://www.gnu.org/software/bc/manual/html_mono/bc.html#TOC... The expression precedence is as follows: (lowest to highest) || operator, left associative && operator, left associative ! operator, nonassociative Relational operators, left associative Assignment operator, right associative + and - operators, left associative *, / and % operators, left associative ^ operator, right associative unary - operator, nonassociative ++ and -- operators, nonassociative This precedence was chosen so that POSIX compliant bc programs will run correctly. This will cause the use of the relational and logical operators to have some unusual behavior when used with assignment expressions. Consider the expression: ... This brings us to the POSIX specification for bc https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/bc.html https://pubs.opengroup.org/onlinepubs/9699919799.2018edition... This also shows the unary - having higher precedence than ^. https://github.com/gavinhoward/bc/blob/master/manuals/development.md https://github.com/gavinhoward/bc/blob/master/manuals/develo... This document is meant for the day when I (Gavin D. Howard) get hit by a bus. In other words, it's meant to make the bus factor a non-issue. This document is supposed to contain all of the knowledge necessary to develop bc and dc. In addition, this document is meant to add to the oral tradition of software engineering, as described by Bryan Cantrill. ... now, it would be interesting if gavinhoward could clarify some of the design thoughts there (and I absolutely love the oral tradition talk).
- JonChesterfield 2y agoFortunately these rules are natural and easy to remember, especially the details of how different languages choose different orders, relative to the confusing and abhorrent prefix notation (- (^ 3 2)) or (^ (- 3) 2).
- shagie 2y agoAs a lover of prefix and postfix notation, there is an unambiguous parsing of each of those that does not deepened on any order of operations. Neither lisp nor forth have the question at all - you can only write it exactly as you mean it. (- (expt 3 2)) is always -9 without needing to ask which has higher precedence. (expt -3 2) is likewise always 9. There is no question if - is a binary or unary operator in prefix notation and what its order of operation should be. Likewise, in dc 3 _ 2 ^ p _3 2 ^ p and 3 2 ^ _ p where '_' is the negation operator (it can be used for writing -3 directly as _3, but _ 3 is a parse error) return their results without any question of order of operations. When you start touching infix, you get into https://en.wikipedia.org/wiki/Shunting_yard_algorithm https://en.wikipedia.org/wiki/Shunting_yard_algorithm which was not a fun part of my compiler class. (And yes, I do recognize your credentials ... I still think that lisp and forth (above examples for dc) are better notational systems for working with computers even if it takes a bit of head wrapping for humans).
- bikenaga 2y agoMaybe something's wrong with my terminal. In dc: 3 _ 2 ^ p gives 0 _3 2 ^ p gives 9 3 2 ^ _ p gives 0 5 _ p gives 0 _5 p gives -5 You didn't intend that I should get those zeros, right?
- shagie 2y ago~ % dc -v dc 6.5.0 Copyright (c) 2018-2023 Gavin D. Howard and contributors Report bugs at: https://git.gavinhoward.com/gavin/bc This is free software with ABSOLUTELY NO WARRANTY. ~ % dc 3 _ 2 ^ p 9 _3 2 ^ p 9 3 2 ^ _ p -9 5 _ p -5 _5 p -5 (control-D) The version that I have appears to have _ parsed as an operator in addition to the negation of a numeric constant.
- bikenaga 2y agoNo - in a subtle way, you're assuming that the unary minus has precedence, when the point is that it doesn't. You're right that "thing^2" means "thing times thing", but in "-3^2", what is it that is being squared? To write it, as you did, as "(-3) x (-3)", assumes that in "-3^2" the thing being squared is "-3". But that in turn assumes that the unary minus is done before the square. By the standard mathematical convention, in "-3^2" the thing being squared is "3". So you do "3 * 3", then you negate the result and get "-9".
- deleted 2y ago[deleted]
- HKH2 2y agoThanks. I had no idea. Seems counterintuitive at first, but it makes sense, since ’-3’ is '0 - 3'.
- setopt 2y agoThis is a good way to think of it. It would be very confusing if “0 - 3^2” and “0 + (-3^2)” should mean different things.
- zmgsabst 2y agoBut what about (0-3)^2? You said that “-3” = “0-3”. So we have “-3^2” is “(0-3)^2” is 9. Agreeing with -3^2 = 9. You’re performing a sleight of hand when you define “-3” to be “0-3”, but move the parenthesis to get your second equation. You have to insert your definition as a single term inside parenthesis — you can’t simply remove them to change association (as you have done). That’s against the rules. So if you think “-3” is “0-3”, then you should agree the answer is 9.
- RandomThoughts3 2y ago> (0-3)^2? It’s entirely unambiguous due to the parenthesis. I don’t think the rest of your argument actually makes sense. There is no sleight of hand required. The original argument is entirely related to having unary minus and binary minus which are different operators conceptually have similar precedence as being less surprising.
- alpinisme 2y agoHow we right negative literals in expressions is the issue. Nobody would seriously think -x^2 = -4 had no non-imaginary solutions. But if we swap out x for a literal number people start interpreting it ambiguously as maybe a negative number exponentiated, but fundamentally it’s the same syntax as before.
- cycomanic 2y agoI had a discussion on one of the Nim boards because Nim does the same, i.e. Writing -2^2=4 but 0-2^2=-4 because Nim treats the first as the unary - which takes precedence over exponentiation. I realise that you can argue how it is technically correct (and interestingly several of the people I was talking with couldn't even get my point), but I still argue it's incredibly unintuitive for anyone coming from an regular engineering/science background who wants to do regular work. I would almost argue will exclude it to be used by many due to this.
- bikenaga 2y agoYou're right that violating established mathematical convention can be a deal-killer for some kinds of adoption. A few years ago I was reading the docs for a new programming language, thinking it might be useful in teaching. The docs were well-written and in a beautifully produced book. I got to the chapter on trig functions and discovered that they'd decided to make angles increase clockwise. And there was a graph of the sine function, with the graph below the x-axis from 0 to 180 degrees. And I sadly put the well-written beautifully-produced book on the shelf and haven't looked at it since. I can see why people would think "angles increase clockwise" is more natural than the existing convention ("angles increase counterclockwise") - it's the way clocks do it, right? Yeah, it's just convention, but when the established convention has been around for at least a century or two and there are libraries full of books and papers which use it, "more natural" still isn't good enough reason to break with it. And it really wasn't necessary to do that for their project. I'm sure people who do software can think of lots of conventions which may even suck but will never be replaced.
- thaumasiotes 2y ago> I got to the chapter on trig functions and discovered that they'd decided to make angles increase clockwise. That is an established mathematical convention, called "bearing". https://en.wikipedia.org/wiki/Bearing_(navigation) https://en.wikipedia.org/wiki/Bearing_(navigation) > And there was a graph of the sine function, with the graph below the x-axis from 0 to 180 degrees. But that definitely isn't a convention anywhere; bearing 0 has sine 1. There isn't really one mathematical convention on "angles". There's a fairly strong one on angles that are named theta, but in a math class it's normal to orient phi in whatever way makes sense to you. As you trace a sphere, do you want phi to represent the angle between (1) the radius ending in your point and (2) the xy plane, as that angle varies from negative pi/2 to pi/2? Do you want it to represent the angle between (1) the radius ending in your point and (2) the positive z axis, as that angle varies from 0 to pi? That's your call. An increase in the angle just means it's getting wider; what direction that requires the angle to grow in depends on how you defined the angle and which of its sides is moving.
- bc_programming 2y agoThis issue seems like partly an artifact of the invented binary operator ^. In math exponents are superscripts and there's no binary operator- it's part of the term. But for text on computers, binary operators ended up being fabricated for the things you couldn't represent directly. The caret is common and was the first one to appear, but doubled multiplication signs is another one. Traditionally, binary operators have lower precedence than unary operators since the unary minus is considered part of the term, so the exponent turning into an operator mucks things up if it's still implemented to adhere to that logic. You sort of see the same issue with division. The forward slash is a completely invented binary operator since the actual division symbol was often not present- and let's be real nobody uses the binary division operator when writing formulae. It's supposed to represent the dividing line in a fraction, similar to how division is usually represented in a formula as a fraction of two other expressions. It's got lower precedence than anything in either term- but, if you just replace the dividing line with a forward slash to input the formula into a computer, you'll get incorrect results, because it's replacing what is part of a complete term (the division line) with a new binary operator inserted between sets of terms, which is now subject to precedence rules.
- fn-mote 2y agoIn my country we teach the same rules in math class. Blaming it on “unary vs binary” was a stretch. Next you’re going to blame it on the lexer for producing the -3 as a single term instead of two. (Which WOULD explain something, but… fix it?!) In my country we use a horizontal line with a dot above and below to indicate in-line division in lower grades. Exactly like the computer /. It’s not like there was no precedent here.
- mark-r 2y agoI also learned the line with a dot above and below in my country, the USA. But that was a very long time ago, math teaching has changed immeasurably since my time. In Unicode it's U+00F7: https://www.compart.com/en/unicode/U+00F7 https://www.compart.com/en/unicode/U+00F7
- MrJohz 2y ago
- kazinator 2y agoIn the C language, -a*b parses as (-a)*b, but c-a*b parses as c-(a*b). Unary minus has a higher precedence than binary operators. You don't notice because the semantics allows the sign to move around, unlike with exponentiation. But when we throw in edge cases involved in undefined behavior, oops! 0 - INT_MIN/2 // fine: parses as 0 - (INT_MIN / 2) -INT_MIN/2 // not okay: parses as (-INT_MIN) / 2 The INT_MIN value need not have an additive inverse because of a quirk in two's complement.
- MaxBarraclough 2y ago> The INT_MIN value need not have an additive inverse because of a quirk in two's complement. For comparison, in Java, these 3 expressions each yield Integer.MIN_VALUE (i.e. -2147483648): -Integer.MIN_VALUE Integer.MIN_VALUE * -1 Integer.MIN_VALUE / -1 I have to admit I expected all 3 to throw. edit On reflection I shouldn't have expected that, I recall reading John Regehr's blog post on the downsides of how Java defaults to wrapping behaviour: https://blog.regehr.org/archives/1401 https://blog.regehr.org/archives/1401
- FabHK 2y agoI recall reading that this was easier to implement in memory constrained machines running Excel back then, and now can't be changed for compatibility. It has bitten me when I computed the pdf of a standard normal in Excel, invoking exp(-A1^2), say. Someone made a website (in 2003, it's a bit out of date) tracking this issue: http://www.macnauchtan.com/pub/precedence.html http://www.macnauchtan.com/pub/precedence.html
- eviks 2y agoBut of course it can be changed, you can make it configurable even if you decide the default should continue be this silly mistake "for compatibility"
- verbify 2y agoIt is configurable - with brackets.
- eviks 2y agoYou confuse configuration with data entry
- tsimionescu 2y agoThere's no "mistake", the current way makes much more sense in programming notation. It's far better that -3^2 is consistent with -3+2. The caret notation for exponentiation is anyway completely different, and works very differently in terms of precedence from using super scripts in math.
- eviks 2y agoThat's a mistake in every statement: Excel isn't programming, so programming notation isn't even relevant There is also no difference in the caret notation vs superscript, its upward pointing form literally meant to signify SUPERscript It's far better that 0-3^2 -3^2 are consistent, consistency between exponent and addition makes little sense since by universal convention they have different priorities, so you'd not expect any "consistency" there Also your -3+2 example is meaningless since its output is the same as -((+3)+2) so there is no inconsistency with -9 And no, ^ doesn't universally work differently vs superscript, just in some poorly designed apps
- Validark 2y agoThis is probably the most overly pedantic, nitpicky reason for not using a program I've ever heard. I'm aware that there are two different conventions on this issue, so I just use parentheses to get the behavior I want. But, growing up, as the top math student in my class, it never occurred to me that somebody out there wants -3^2 to equal -9, I thought it was just a weird quirk in some calculators/programs. How would you read that expression aloud? I think of it as "negative three squared" so that's why (-3)^2 makes sense to me. Do you say "the negative of three squared"? In 8th grade, I remember being instructed to type such an expression into the calculator to observe how it does something contrary to what we expect it to. From that moment on, I thought, "Huh, guess you have to use parentheses." It certainly wasn't cause enough to throw out my calculator, let alone tell others not to use it, just because I prefer a slightly different precedence convention.
- lionkor 2y ago"minus (pause) three squared"
- archargelod 2y agoI think we should agree that standard notation is too ambigious and switch to reverse polish notation: 3 2 ^ - -9 3 - 2 ^ 9 No way to misinterpret that!
- kqr 2y agoExcept 3 - 2 ^ makes it hard to express 3 2 - ^ without accidentally subtracting, so in this case a unary negation sign needs to be a different symbol!
- kstrauser 2y agoI dug out my HP 50g over the weekend to play with, and conveniently… Sigh. I understand why we commonly enter math on basically a teletype-with-ASCII, and I don’t have an urge to go all APL, but for a while we were so close to a future where we could’ve had separate negation or multiplication or exponentiation symbols that might’ve removed so much room for error. I mean, that little calculator and its predecessors were popular and widely used by the same people who brought us things like Unicode and the space cadet keyboard. If only one of them had said, gee, it sure would be handy to have a +- key on the keyboard the person in the next cubicle is designing as I have on the calculator on my desk! But nope, Everything Is ASCII won and here we are. At least programming languages are starting to support Unicode identifier names, which has its own issues but is excellent for non-Latin alphabet users who want to write code in their own tongue. It seems like a reasonably short hop from there to giving operators their own unambiguous names. I can imagine a near-distant future where a linter says “you typed -3. Did you mean ⁻3?”, to the chagrin of programmers still entering their code on teletypes.
- AtNightWeCode 2y agoThe exponent operator is just short for the POWER function in Excel. So from that perspective it is the correct behaviour I think even if it is mathematical incorrect.
- deleted 2y ago[deleted]