Order of operations for logic operations?

1.3k Views Asked by At

I have some code, that does a comparison to find how many of set of values fall within a range defined by a mean±sd, like this:

sum(mean - sd < value & value < mean + sd )

Most discussions of the order of operations only include basic functions (PEDMAS - parentheses, exponentials, division, multiplication, addition and subtraction). This says nothing about the order of operations for boolean functions or comparisons. Obviously I could clarify things with some parentheses:

sum(((mean - sd) < value) & (value < (mean + sd)))

In the language I was using (R), this happened to work exactly the same anyway, but I wasn't sure if that is something I should take for granted. Is there a standard language-agnostic order of operations that includes arithmetic operators and logical operators? Are there other operations that should be included in such a list?

2

There are 2 best solutions below

0
On

To the best of my knowledge, there is no standard order of operations for this -- it will vary for every language you use, and in mathematical logic, this is generally clarified with parentheses, as you have done.

0
On

Even in mathematics, this may depend on context. In analysis or number theory, say, $a<b \land c<d$ is likely to be read as $(a<b)\land(c<d)$, whereas in lattice theory it may well be read as $a<(b\wedge c)<d$. So yes, it's always best to parenthesize defensively when in doubt.

Edit: In the first case, $\land$ means "logical and", while in the second case, $\wedge$ means "meet" (that is, the infimum of two values). The two meanings are actually related in a deep and useful way, but their "surface meanings" are quite different and they have different natural precedence in terms of the order of operations.