Data Representation

As we explored in lecture, what we see when we look at binary data entirely depends on what we’re looking for. Consider the following example, where we write the numbers 1 to 128 in the system’s native binary format to a file:

writeBin(1:128, con = "out.bin", size = 1)

Open the resulting file in a text editor, and see how the bytes are interpreted as ASCII.

Try the following examples and look at the output (note that we close the connection each time, because otherwise we’ll keep reading through the file rather than starting at the beginning):

A. One Byte Integers (correct representation, sometimes called a “char”)

connection <- file("out.bin","rb")
readBin(con = connection, what = "int", n = 10, size = 1)
close(connection)

B. Two Byte Integers (called “short”)

connection <- file("out.bin","rb")
readBin(con = connection, what = "int", n = 10, size = 2)
close(connection)

C. Four Byte Integers (typical int representation)

connection <- file("out.bin","rb")
readBin(con = connection, what = "int", n = 10, size = 4)
close(connection)

D. Eight Byte Floating Point (typical “double” representation)

connection <- file("out.bin","rb")
readBin(con = connection, what = "double", n = 10, size = 8)
close(connection)

Exercise: Show why the first element of part B is equal to 513. Hint: consider what the first two bytes in the file look like, and how they would be interpreted as a base-2 integer.

Storing Stuff in Memory

It’s easy, when your data is small relative to the amount of RAM you have available, to ignore how information is stored in computer memory (RAM) and on the hard drive. It’s also easy to forget that R is what’s known as a ‘high-level’ language, meaning there’s a lot of machinery in place; simple things may involve more work for the computer than is at-first apparent.

In the examples below, we’ll try storing various data types in memory and on-disk, and seeing how much space is used. See if you can figure out why these exhibit different behaviors.

Character/String Data

character_data <- data.frame(num_char = 1:200,
                             char_size = NA,
                             vec_size = NA)

for (i in 1:nrow(character_data)){
  example_vec <- rep("A", i)
  example_str <- paste(example_vec, collapse = "")
  character_data$vec_size[i] <- object.size(example_vec)
  character_data$char_size[i] <- object.size(example_str)
}


# How does the vector size grow as we add more elements?
with(character_data, plot(num_char, vec_size))
# What does this look like as a change-value?
with(character_data, plot(num_char[2:nrow(character_data)], diff(vec_size)))
abline(h = seq(0,64,8), lty = 2, col = "lightgrey")
# How does the character size grow as we add more elements?
with(character_data, plot(num_char, char_size))
# What does this look like as a change-value?
with(character_data, plot(num_char[2:nrow(character_data)], diff(char_size)))
abline(h = seq(0,64,8), lty = 2, col = "lightgrey")

As we expect, the object sizes grow as the objects grow, but it’s not strictly linear. What would you hypothesize might be the reason/purpose for such behavior?

Numeric Data

numeric_data <- data.frame(num_terms = 1:200,
                           num_size = NA,
                           vec_size = NA)

for (i in 1:nrow(numeric_data)){
  example_vec <- rep("1", i)
  example_num <- as.numeric(paste(example_vec, collapse = ""))
  numeric_data$vec_size[i] <- object.size(as.numeric(example_vec))
  numeric_data$num_size[i] <- object.size(example_num)
}


# How does the vector size grow as we add more elements?
with(numeric_data, plot(num_terms, vec_size))
# What does this look like as a change-value?
with(numeric_data, plot(num_terms[2:nrow(numeric_data)], diff(vec_size)))
abline(h = seq(0,64,8), lty = 2, col = "lightgrey")
# How does the size grow as we add more digits?
with(numeric_data, plot(num_terms, num_size))
# What does this look like as a change-value?
with(numeric_data, plot(num_terms[2:nrow(numeric_data)], diff(num_size)))

File Size on Disk

Based on what we’ve seen so far, we can now see why data contained in files on disk might behave differently than that which we load into RAM with a particular representation. Let’s test this idea out

# Function to create a file with n bytes of data (each character in an ASCII file is one byte)
create_N_digit_file <- function(n, filename = "test_file.txt"){
  if (n <= 0){
    stop("What are you trying to accomplish?")
  }
  cat(paste(rep("0", n), collapse = ""), file = filename)
  # Always end ASCII files with a newline character
  cat("\n", file = filename, append = TRUE)
}


file_data <- data.frame(num_digits = 1:200,
                        file_size = NA)

for (i in 1:nrow(numeric_data)){
  create_N_digit_file(i)
  file_data$file_size[i] <- file.size("test_file.txt")
}


# How does the vector size grow as we add more elements?
with(file_data, plot(num_digits, file_size))
# What does this look like as a change-value?
with(file_data, plot(num_digits[2:nrow(numeric_data)], diff(file_size)))

Files behave like we’d expect - we’re just writing data in a particular format to the hard disk of the computer. Let’s try reading each of these files back into R and converting the data back to numeric, to see what the difference in storage size is:

memory_data <- data.frame(num_digits = 1:200,
                        size_in_mem = NA)

for (i in 1:nrow(numeric_data)){
  create_N_digit_file(i)
  # Read in the file as text
  dat <- readLines("test_file.txt")
  # Convert each digit to numeric, very much like what tends to happen in read.csv
  numeric_data <- as.numeric(strsplit(dat, split = "")[[1]])
  memory_data$size_in_mem[i] <- object.size(numeric_data)
}

# How does the vector size grow as we add more elements?
with(memory_data, plot(num_digits, size_in_mem))
# What does this look like as a change-value?
with(memory_data, plot(num_digits[2:nrow(memory_data)], diff(size_in_mem)))
# How does this compare - file size to in-memory size?
plot(file_data$file_size, memory_data$size_in_mem)
plot(memory_data$size_in_mem/file_data$file_size)

Note that the ratio plotted in this section approaches eight: we’re moving from data stored in one byte per number to numeric data stored as double precision floating point numbers with eight bytes per number.

Numerical Precision

Working with computer numbers is different from working with real numbers, for more reasons than just the way they’re stored and displayed. Consider the following examples.

# Things that R shows to us as being equal are not always equal
print(1e10 + 1000)
print(1e10)
print(1e10 + 1000 == 1e10)

# Make R show the full displayable base-10 precision, to see why
options(digits=22)
print(1e10 + 1000)

# Sometimes these things *are* equal. In this case, we're running out of precision:
print(1e19 + 1000)
print(1e19)
print(1e19 + 1000 == 1e19)

# Working with numbers of different magnitudes is problematic
print((1e-6 + 1e10) -1e10 - 1e-6)

# Another Example:
0.1+1e17-1e17-0.1

# Some numbers can't be represented exactly in base 2 at all:
0.1

# These kind of problems get MUCH worse, depending on what kind of algorithm they're embedded in:
zero <- 0
for (i in 1:1000){
  zero <- zero + 1000*((1e-6 + 1e10) -1e10 - 1e-6)
}
print(zero)

These issues are important, even for simple statistical operations.

For example, consider that, for a sample \(\{x_i, i=1,...,n\}\), we know that the sample variance has the form:

\(var({\bf x}) = \frac{1}{n-1}\sum_{i=1}^n(x_i - \bar{\bf{x}})\) \(=\frac{1}{n-1}\sum_{i=1}^n(x_i^2 - 2x_i{\bar{\bf{x}}} + {\bar{\bf{x}}}^2)\) \(=\frac{1}{n-1}\left(\sum_{i=1}^n(x_i^2) - n{\bar{\bf{x}}}^2)\right)\)

These expressions are not, however, equivalent to a computer.

variance1 <- function(x){
  (1/((length(x))-1))*sum((x-mean(x))^2)
}

variance2 <- function(x){
  ((1/((length(x))-1))*sum(x^2) - (1/((length(x))-1))*length(x)*mean(x)^2)
}

variance3 <- function(x){
  ((1/((length(x))-1))*(sum(x^2) - length(x)*mean(x)^2))
}


dat <- rnorm(10000, mean = 1e6, sd = 0.0001)
variance1(dat)
variance2(dat)
var(dat)


## The magnitude of numbers is important
dat <- rnorm(10000, mean = 1e6, sd = 1)
variance1(dat)
variance2(dat)
var(dat)

A more common example is likelihood evaluaton. Consider the following, very tractable problem:

## True but unknown data generating mechanism
X <- rnorm(100, mean = 5, sd = 1)
## Estimate for mu:
mu_hat <- mean(X)
## Pretend that we know the true sigma, and evaluate the likelihood around mu hat:


X.prime <- seq(mu_hat - 2, mu_hat +2, length = 1000)
plot(X.prime, sapply(X.prime, function(xp){prod(dnorm(X, mean = xp, sd = 1))}))

What happens when we increase the sample size?

## True but unknown data generating mechanism
X <- rnorm(10000, mean = 5, sd = 1)
## Estimate for mu:
mu_hat <- mean(X)
## Pretend that we know the true sigma, and evaluate the likelihood around mu hat:


X.prime <- seq(mu_hat - 2, mu_hat +2, length = 1000)
plot(X.prime, sapply(X.prime, function(xp){prod(dnorm(X, mean = xp, sd = 1))}))

This is most commonly addressed by working on the log scale, which:

  1. Makes our numbers smaller, increasing precision
  2. Lets us work with addition operations rather than multiplication, which is more stable
## True but unknown data generating mechanism
X <- rnorm(10000, mean = 5, sd = 1)
## Estimate for mu:
mu_hat <- mean(X)
## Pretend that we know the true sigma, and evaluate the likelihood around mu hat:


X.prime <- seq(mu_hat - 2, mu_hat +2, length = 1000)
plot(X.prime, sapply(X.prime, function(xp){sum(dnorm(X, mean = xp, sd = 1, log = TRUE))}))

Much better!

When you implement algorithms, numerical stability is a critical concern. This concern will grow whenever:

  1. The algorithm or some step within it is unstable
  2. The data size becomes large

Testing for Equality

With these phenomena in mind, it should now be clear why it is never recommended to test for equality using floating point numbers.

0.1 == (0.1 + 0.2 - 0.2)
## [1] FALSE

Instead, if you ever need to compare the result of two floating point calculations, you should use some epsillon comparison:

approx_eq <- function(a,b){
  abs(a-b) < 2*.Machine$double.eps
}

approx_eq(0.1, 0.1 + 0.2 - 0.2)
## [1] TRUE

Supplemental reading: Machine Epsilon

We’ll return to these concepts throughout the course.