Order of equation evaluation
Order of equation evaluation follows BIDMAS aka PEMDAS
The other day I saw a discussion about an equation and started writing this post, it then came up again recently on CFML Slack, so thought I’d finish off the post in case it’s of interest.
Consider the following code:
result = 8 / 2 * ( 2 + 2 );
What would you expect the outcome of that to be?
What if I flipped it around like so – would I get the same answer?
result = ( 2 + 2 ) * 8 / 2;
Depending on how you write an equation it can be tricky to know what the outcome will be, but there is only one correct answer (in code terms at least before Sean and Ross on CML Slack start talking about fractional brackets!) and I thought it was worth posting an example in case people weren’t aware of the order of evaluation of expressions in your CFML code.
The answer to both of the above is 16.
The rules which dictate the order of evaluation are consistent and is commonly taught (in the UK at least) using the acronym BIDMAS (or sometimes BODMAS) which stands for:-
Brackets, Indices, Division / Multiplication, Addition / Subtraction.
According to Sean on CFML slack, in the US this is taught as PEMDAS:-
Parentheses, Exponents, Multiplication / Division, Addition / Subtraction.
The sharp eyed reader may note that the Division / Multiplication order is different in PEMDAS to BIDMAS. More on that later.
Using the above equation, this means that order of evaluation is firstly the brackets:
8 / 2 * ( 2 + 2 ); => 8 / 2 * ( 4 );
Next up is indices, we don’t have any (indices being exponents, meaning to the power of, such as squared), so we can move on to division / multiplication. As the division is the first thing we see reading left-to-right, the division happens next.
8 / 2 * 4; => 4 * 4;
Now we do the multiplication to get the answer:
4 * 4; => 16;
The order of evaluation for the flipped example is:
( 2 + 2 ) * 8 / 2; => ( 4 ) * 8 / 2; // evaluated brackets => 4 * 8 / 2; // evaluated indices (none so no change) => 32 / 2; // evaluated multiplication => 16; // evaluated division
Here’s an example that uses all operations in the acronym:
x = 10 + 8 / 2 ^ 3 * ( 2 + 2 ) - 5; writeDump(x); // 9 x = 10 + 8 / 2 ^ 3 * ( 4 ) - 5; // [b]idmas x = 10 + 8 / 8 * 4 - 5; // b[i]dmas x = 10 + 1 * 4 - 5; // bi[dm]as x = 10 + 4 - 5; // bi[dm]as x = 14 - 5; // bidm[as] x = 9; // bidm[as] writeDump(x); // 9
You do need to be a bit careful with the acronyms to remember the order as with multiple/divide and addition/subtraction operations the order in the equation matters as shown in this example:
10 - 3 + 2 // 9 3 + 2 - 10 // -5
More info here: https://en.wikipedia.org/wiki/Order_of_operations
Thanks to Sean, Ross and Mingo on the CFML Slack for the discussion!