Blog of Andrés Aravena
CMB2:

Some answers to Homework 5

05 May 2021

Some students have been generous and shared their answers to homework – after the deadline, of course. Here you can see their answers and some of my comments.

These are some of the answers to Homework 5. We will share more homework answers later. If you want to share your homework’s answers, send me an email.

Most of the students prefer that answers are published anonimously. At the end, it is easier and better that all answers are shown without disclosing the author.

<!– # 1. Write a recursive code
# 2. Write a non-recursive version
# 3. Find the best-fitting line
## 4. Find the formula
::: q4 # It noticed that connecting amount of all rabbits and kind of two rabbits which is young and old. :::
—– –> ::: marginnote # Student 2 :::
# 1. Write a recursive code
# 2. Write a non-recursive version ```r fib_loop <- function(n){ young <- rep(NA, n) old<- rep(NA, n) young[1] <- 1 old[1] <- 1 old[2] <- 1 for(i in 3:n){ young[i] <- old[i] old[i] <- old[i-1] + old[i-2]
} return(tail(old, n=1)) } ```
# 3. Find the best-fitting line
r model <- lm(log(y) ~ n) 100*(exp(coef(model))-1)

Student 3

1. Write a recursive code

fib_recursive <- function(n) {
if(n==0) {
    ans <- 0
} else {
  if(n==1) {
    ans <- 1
  } else {
    ans <- fib_recursive(n-1) + fib_recursive(n -2)
  } 
  return(ans)
}
}

2. Write a non-recursive version

fib_loop <- function(n) {
  young <- rep(NA, n)
  old <- rep(NA, n)
  old[1] <- 1
  old[2] <- 1
  for(i in 3:n) {
    young[i] <- old[i-2]
    old[i] <- old[i-1] + young[i]
  }
  print(old[n])
}

3. Find the best-fitting line

library(readr)
library(ggplot2)
y <- fib_recursive
index <- seq(1, 30)
line <- sapply(index, y)
model <- lm(log(line) ~ index)
coef(model)
plot(line)
abline(a=coef(model)[1], b=coef(model)[2])

4. Find the formula

formula <- function(n) { exp(coef(model)[1] + coef(model)[2]*n) }
formula

y = exp(coef(model)[1] + coef(model)[2]*n)

y = exp(-0.7768359 + 0.4798524*n)

::: marginnote # Student 4 :::
# 1. Write a recursive code

Student 5

1. Write a recursive code

fib_recursive <- function(n) {
  if(n == 0 | n == 1)
    return(n)
  else {
    return(fib_recursive(n - 1) + fib_recursive(n - 2))
  }
}

2. Write a non-recursive version

fib_loop <- function(n) {
old <- rep(NA, n)
young <- rep(NA, n)
old[1] <- 0
young[1] <- 1
old[2] <- 1
young[2] <- 0
  if (n == 0)
    return(n)
  else {
    for (i in 3:n) {
      old[i]=old[i - 1]+old[i - 2]
      young[i]=young[i - 1]+young[i - 2]
    }
    total <- old[i] + young[i]
  }
return(total)
}
fib_loop(12)

3. Find the best-fitting line

y <- rep(NA, 30)
for (i in 1:length(y)) {
  y[i] <- fib_recursive(i)
}
n <- 1:30
plot(log(y) ~ n)
model <- lm(log(y) ~ n)
coef(model)
abline(model, col= "red")

4. Find the formula

The formula is y = coef(model)[1] + coef(model)[2].n

Originally published at https://anaraven.bitbucket.io/blog/2021/cmb2/hw5-answers.html