Skip to content

Instantly share code, notes, and snippets.

@nwstephens
Last active June 18, 2016 10:58
Show Gist options
  • Select an option

  • Save nwstephens/64ce23c9920e18dc7a22bf6d64a76f66 to your computer and use it in GitHub Desktop.

Select an option

Save nwstephens/64ce23c9920e18dc7a22bf6d64a76f66 to your computer and use it in GitHub Desktop.
title Long Running Calculations
output html_notebook

The following examples execute long running jobs in R.

1. Sleep

This sequence will output integers from 1 to 120 once per second for 2 minutes.

for(i in 1:120){
  cat(i,'\n')
  Sys.sleep(1)
}

2. Calculate Prime Numbers

This sequence will recursively calculate and output prime numbers between 1 and 1 million.

is.prime <- function(n) n == 2L || all(n %% 2L:floor(sqrt(n)) != 0)
for(i in 1:1000000){
  if(is.prime(i <- i + 1)) cat(i, ' ')
}

3. Calculate Fibonacci Sequence

This sequence will calculate the first 100 elements of the Fibonacci Sequence.

fibR <- function(n) {
    if (n == 0) return(0)
    if (n == 1) return(1)
    return(fibR(n - 1) + fibR(n - 2))
}
for(i in 1:100) cat(i, ':', fibR(i), '\n')

4. Calculate Pi

This sequence will approximate Pi over 1 million iterations.

set.seed(123454321)

piApprox <- function(n) {
  u <- runif(n, -1, 1)
  v <- runif(n, -1, 1)
  w <- u ^ 2 + v ^ 2 <= 1
  x <- 4 * sum(w)
  c(x = x, n = n)
}

out <- numeric(2)
for(i in 1:1000000){
  out <- out + piApprox(99999)
  piEst <- out['x'] / out['n']
  cat(i, piEst, piEst - pi, fill = T)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment