2
$\begingroup$

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?

$\endgroup$
2
  • 1
    $\begingroup$ Unless entirely obvious, it behooves you to be explicit (parenthetically speaking, of course). $\endgroup$
    – copper.hat
    Sep 16 '13 at 5:56
  • 1
    $\begingroup$ In R, addition and subtraction have higher precedence than comparison, which in turn has higher precedence than logical AND - that's why it worked. But as qaphla states, it's language specific. See here: stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html $\endgroup$
    – Bitrex
    Sep 16 '13 at 5:56
2
$\begingroup$

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.

$\endgroup$
2
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.