appScience software

disclaimer

fc31024

The order of evaluation of math

Mathematical expressions are evaluated by formula calculator in the usual order. Each line is evaluated as it is encountered from top to bottom. Expressions in brackets are evaluated first, and this includes any expressions that appear within the brackets of functions, such as cos(2*pi).

The order of evaluation from first to last is:

  1. Functions, such as cos(x), pow(x,2), ...
  2. The power operator ^. This is evaluated right to left, so 3^2^4 is 3^(2^4)
  3. Factorial ! such as 4! which is the same as 4*3*2*1
  4. Implicit multiplications like 2x which is interpreted as 2*x or x y which is treated as x*y
  5. Multiplication and division
  6. Addition and subtraction
  7. Assignment using =

Within each category, expressions are evaluated left to right. A common trap is not using brackets on division. For example, if you want to divide 12 by 3*4, writing 12/3*4 is not correct as this is evaluated like (12/3)*4. Instead you should write 12/(3*4)

With the power ^ and factorial ! operators, negative numbers are treated differently depending on context. A negative number is represented by a minus sign followed by the number, as in -3. If such a number appears at the beginning of a line or after an opening bracket '(' then it is treated as a truly negative quantity, so that -3^0.5 is equivalent to (-3)^0.5 which yields a complex number. However, if the number appears after an expression, like 5-3^0.5 then this is treated as a positive number being subtracted. In this case 5-3^0.5 is equivalent to 5-(3^0.5) which does not yield a complex number. If there is any doubt, use brackets to make your intention clear.