Mathematical Operations
1 Order of mathematical operations
- Mathematical operations are performed from left to right in a specific order as depicted in the following figure:
- This sequence can be memorized using the acronym PEMDAS.
Calculate \(\displaystyle 2\times(3+4)-6 \times 4^2\)
\[ 2 \times(3+4)-6 \times 4^2 = \]
\[2 \times(7)-6 \times 4^2=\]
\[ \\2 \times(7)-6 \times 16 = \]
\[ \\14-96= -82 \]
\[ (3+\frac{4}{2})^3-\sqrt{4\times9}\times2+2 = \]
\[ (3+2)^3-\sqrt{4\times9}\times2+2 = \]
\[ (5)^3-\sqrt{4\times9}\times2+2= \]
\[ 125-\sqrt{4\times9}\times2+2= \]
\[ 125-\sqrt{36}\times2+2= \]
\[ 125-6\times2+2= \]
\[ 125-12+2=115 \]
The answer is
2 Using R as calculator
These calculations can be performed easily in R.
The different operators used in R for mathematical operations are shown in the table below:
Operation | Operator |
---|---|
Addition | \(+\) |
Subtraction | \(-\) |
Multiplication | \(*\) |
Division | \(/\) |
Exponentiation | ^ or \(**\) |
Integer division (returns result as integer discarding any remainder) | \(\text{\%/\%}\) |
Modulo (returns the remainder of division) | \(\text{\%\%}\) |
- Now, let’s try to calculate the expression in Exercise M.1.1 using R to make sure that we get the same answer:
Click to show/hide code
3+4/2)^3-(4*9)^0.5*2+2 # option 1: raising to the power 0.5 (
[1] 115
Click to show/hide code
3+4/2)^3-sqrt(4*9)*2+2 # option 2: using sqrt() function (
[1] 115
Click to show/hide code
10/3 # division
[1] 3.333333
Click to show/hide code
10 %/% 3 # integer division
[1] 3
Click to show/hide code
10 %% 3 # modulo
[1] 1
Click to show/hide code
4/2*3
[1] 6
In this expression, division precedes multiplication.
When different operators have the same precedence, they are evaluated according to the order they appear from left to right.
Write an R code to calculate Exercise M.1.2
Click to show/hide code
1^2+5^2+7)/(4-1) (
[1] 11
3 References
Bougioukas, K., I. Practical Statistics in Medical Research with R. Retrieved August 09, 2024, from https://practical-stats-med-r.netlify.app/
Order of Operations. Statistics Online, Pennsylvania State University, Eberly College of Science. Retrieved August 09, 2024, from https://online.stat.psu.edu/statprogram/reviews/algebra/order-of-operations