Search code examples
javascriptmathoperator-precedence

Can Javascript ever violate the mathematical PEMDAS convention?


I was taught that in maths we evaluate things, with the acronym BODMAS Brackets, Orders(powers), Division, Multiplication, Addition, Subtraction.

I understand that in Javascript, * and / have equal precedence. + and - do too. And left associativity is used.

From the few examples I can think of, it seems to work just as well, producing the same results as BODMAs.

It looks like in the reality of the mathematical rules, it doesn't matter whether addition or subtraction is done first. It can matter whether additional or subtraction can done first 5-2+3. And for division and multiplication, it seems like it's only an issue when division is left of multiplication like 9/3*4 then division must be done first. And Javascript does / first in that instance.

But maybe there is an example where it breaks it! Where it gives a different result to standard maths.

Can Javascript break logical mathematical rules?

UPDATE-

To answer myself, when in Mathematics one says, PEDMAS where D and M are equal precedence and done left to right. And ditto A and S. You are saying they're left associative, i.e. where the implied brackets are. So programming languages that 'implement PEDMAS' the priority/precedence, and DM and AS being left associative, are totally following the PEDMAS rule. So, if there is any breaking of mathematical rules, it isn't from the associativity of M,D,A,S which is the same as in (conventional) mathematics. Also, in Mathematics, the unary minus is here- PEUDMAS so -5^2=-(5^2)=-25. exponent takes priority over unary minus. Though javascript probably gets that right. Apparently floating points in javascript break rules, as shown in some answers, though that wasn't what I had in mind as what I had in mind was purely re PEDMAS, but it seems parentheses make a difference with floating point numbers, where they shouldn't in normal mathematics, as shown in the answer I accepted.


Solution

  • The only problem is with float numbers where the approximation of a division is extremely buggy. An actual example of this would be the fact that this will always alert false:

    var a = 0.1;
    var b = 0.2;
    var c = 0.3;
    if((a+b)+c == a+(b+c))
        alert("true");
    else
        alert("false");
    

    So basically the problem is with the Number object but not with the theoretical math implemented. As a programmer you probably understand the difference of the pre and post incrementation and the order of the operators so I do not really understand why did you gave as example 9/3*4 where the logic of the programmer applies and is verbose with the actual math.

    Finally the answer you seek ( probably just out of curiosity ) is that the actual logic of the math you know it has not been changed in JavaScript, just some bugs from the roots of this language which still haunts us today.