Math 101

Did you ever see one of those trivial sums on Facebook, which looked so easy and yet you knew there must be some trick going on? Something like:

3 + 2 × 6 = ???

Well, you’re right.

Because we, in English, read from left to right. But in math, you don’t. In math, you work certain sums out before others, and not necessarily in the same order that they appear on the page. This is a standard mathematical idea, usually called the order of precedence, Wikipedia talks about it here. So, something like a × happens before a +, and so on. Working in computing I’ve come across this a lot, and the rules in full are pretty verbose, but the basic thing is that you perform some operations before others. Left or right matters less. It matters for some things, like ÷, but mostly, no.

So, if somebody presented me with a line of computer code which said,

3 + 2 × 6

the first thing, I would probably fail its review, because it is ambiguous. In fact, it should be written as

3 + (2 × 6)

which gives the exact same result, but by introducing the brackets, you make it obvious. It’s easier for the reader to see what is going on, and that has always been my #1 aim when reviewing computer code.

The bracket says perform me first, so you can see we are no longer in the realm of left-to-right.

Once you realise that, the answer is trivial.

3 + 2 × 6 = 3 + (2 × 6) = 15

Easy, huh? But not so easy as you might think. Even Microsoft’s own calculator (on my PC) gets the sum wrong, unless I help it out by adding the brackets.

8 comments

Leave a Reply to Peter's pondering Cancel reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s