# Basic arithmetic and logic

## R as a pocket calculator

### Arithmetic operators

See help(Arithmetic)

3 + 7
[1] 10
9 / 3
[1] 3
12^2 + 1.5*10
[1] 159
10 %/% 3
[1] 3
10 %% 3
[1] 1

Also see help(Syntax) for operator precendence / associativity: This determines the order in which computations are carried out when multiple operators are present. Use parentheses to make execution order explicit.

9 * (3+2)
[1] 45
(9*3) + 2
[1] 29

Using operators in function notation

"/"(1, 10)
[1] 0.1
"+"(2, 3)
[1] 5

### Standard math functions

sqrt(4)
[1] 2
sin(pi/2)
[1] 1
abs(-4)
[1] 4
log10(100)
[1] 2
exp(1)
[1] 2.718282

### Rounding numbers

round(1.271)
[1] 1
round(pi, digits=3)
[1] 3.142
ceiling(1.2)
[1] 2
floor(3.7)
[1] 3
trunc(22.913)
[1] 22

### Complex numbers

exp(1)^((0+1i)*pi)
[1] -1+0i
exp(1)^(-pi/2) - (0+1i)^(0+1i)
[1] 0+0i
sqrt(-1)
[1] NaN
sqrt(-1+0i)
[1] 0+1i

### Special values

.Machine$integer.max [1] 2147483647 .Machine$double.eps
[1] 2.220446e-16
1/0
[1] Inf
is.infinite(1/0)
[1] TRUE
0/0
[1] NaN
is.nan(0/0)
[1] TRUE
NULL
NULL
is.null(NULL)
[1] TRUE

### Using variables (objects)

x1 <- 2
x2 <- 10
x3 <- -7
x1 * 2
[1] 4
x2^x1 + x3
[1] 93

## Logic

### Logical values

TRUE
[1] TRUE
FALSE
[1] FALSE
!TRUE
[1] FALSE
!FALSE
[1] TRUE
isTRUE(TRUE)
[1] TRUE
isTRUE(FALSE)
[1] FALSE

### Logical comparisons

TRUE == TRUE
[1] TRUE
TRUE == FALSE
[1] FALSE
TRUE != TRUE
[1] FALSE
TRUE != FALSE
[1] TRUE
TRUE & TRUE
[1] TRUE
TRUE & FALSE
[1] FALSE
FALSE & FALSE
[1] FALSE
FALSE & TRUE
[1] FALSE
TRUE | TRUE
[1] TRUE
TRUE | FALSE
[1] TRUE
FALSE | FALSE
[1] FALSE
FALSE | TRUE
[1] TRUE
xor(TRUE, FALSE)
[1] TRUE
xor(TRUE, TRUE)
[1] FALSE

Short-circuit logical comparisons with vectors

c(TRUE,  FALSE, FALSE) && c(TRUE,  TRUE, FALSE)
[1] TRUE
c(FALSE, FALSE, TRUE)  || c(FALSE, TRUE, FALSE)
[1] FALSE

### Arithmetic comparisons

4 < 8
[1] TRUE
7 < 3
[1] FALSE
4 > 4
[1] FALSE
4 >= 4
[1] TRUE

### Checking whether any or all elements are TRUE

any(c(FALSE, FALSE, FALSE))
[1] FALSE
any(c(FALSE, FALSE, TRUE))
[1] TRUE
all(c(TRUE, TRUE, FALSE))
[1] FALSE
any(c(TRUE, TRUE, TRUE))
[1] TRUE

In an empty vector, there is no element that is FALSE, therefore:

all(numeric(0))
[1] TRUE

In an empty vector, you cannot pick an element that is TRUE, therefore:

any(numeric(0))
[1] FALSE

## Numeric representations

### Integers vs. decimal numbers

4L == 4
[1] TRUE
identical(4L, 4)
[1] FALSE

### Floating point arithmetic

0.1 + 0.2 == 0.3
[1] FALSE
1 %/% 0.1
[1] 9
sin(pi)
[1] 1.224647e-16
1 - ((1/49) * 49)
[1] 1.110223e-16
1 - ((1/48) * 48)
[1] 0

What every computer scientist should know about floating-point arithmetic

### Checking decimal numbers for equality

isTRUE(all.equal(0.123450001, 0.123450000))
[1] TRUE
0.123400001 == 0.123400000
[1] FALSE
all.equal(0.12345001, 0.12345000)
[1] "Mean relative difference: 8.100445e-08"
isTRUE(all.equal(0.12345001,  0.12345000))
[1] FALSE