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
<- function(n) {
fib_recursive if(n==0) {
<- 0
ans else {
} if(n==1) {
<- 1
ans else {
} <- fib_recursive(n-1) + fib_recursive(n -2)
ans
} return(ans)
} }
2. Write a non-recursive version
<- function(n) {
fib_loop <- rep(NA, n)
young <- rep(NA, n)
old 1] <- 1
old[2] <- 1
old[for(i in 3:n) {
<- old[i-2]
young[i] <- old[i-1] + young[i]
old[i]
}print(old[n])
}
3. Find the best-fitting line
library(readr)
library(ggplot2)
<- fib_recursive
y <- seq(1, 30)
index <- sapply(index, y)
line <- lm(log(line) ~ index)
model coef(model)
plot(line)
abline(a=coef(model)[1], b=coef(model)[2])
4. Find the formula
<- function(n) { exp(coef(model)[1] + coef(model)[2]*n) }
formula 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
<- function(n) {
fib_recursive if(n == 0 | n == 1)
return(n)
else {
return(fib_recursive(n - 1) + fib_recursive(n - 2))
} }
2. Write a non-recursive version
<- function(n) {
fib_loop <- rep(NA, n)
old <- rep(NA, n)
young 1] <- 0
old[1] <- 1
young[2] <- 1
old[2] <- 0
young[if (n == 0)
return(n)
else {
for (i in 3:n) {
=old[i - 1]+old[i - 2]
old[i]=young[i - 1]+young[i - 2]
young[i]
}<- old[i] + young[i]
total
}return(total)
}fib_loop(12)
3. Find the best-fitting line
<- rep(NA, 30)
y for (i in 1:length(y)) {
<- fib_recursive(i)
y[i]
}<- 1:30
n plot(log(y) ~ n)
<- lm(log(y) ~ n)
model coef(model)
abline(model, col= "red")
4. Find the formula
The formula is y = coef(model)[1] + coef(model)[2].n