# STAT_540_Lec_R_05.R # The while loop!! # we can always write a while loop instead of a for loop. # here we don't really NEED a while loop, but just # to demonstrate, let's compute the sum with a while loop x <- c(3,7,8,5,1,4,6,7) # for loop: n <- length(x) val <- 0 for(i in 1:n){ val <- val + x[i] } val # let's do the same loop but as a while loop: i <- 1 val <- 0 while(i <= n){ # this will not run once i = n + 1 val <- val + x[i] i <- i + 1 # increment the index } val # division: A / B. # Here we need a while loop because we don't know how many iterations it will have to run. div <- function(A,B){ Q <- 0 while(A >= B){ A <- A - B Q <- Q + 1 } output <- list(quotient = Q, remainder = A) return(output) } div(76,3) # while loop for paying off a debt: B <- 10000 # borrow 10k $$$$$$ for something r <- 0.05 # annual interest rate (compounded monthly) p <- 200 # amount you pay every month m <- 0 while(B >= 0){ B <- B*(1 + r/12) - p m <- m + 1 } m # number of months to pay off the loan m/12 # number of years # Newton's method for finding a root # (value of r for which f(r) = 0) f <- function(r,P,p,n){ (P / p) * (1 + r)^n * r - (1 + r)^n + 1 } df <- function(r,P,p,n){ (P / p) * (n *(1 + r)^(n-1) * r + (1 + r)^n) - n*(1+r)^(n-1) } P <- 10000 # 10 k $$ p <- 200 # monthly payment n <- 60 # number of months to pay off x <- 0.05/12 # initial guess of monthly interest rate conv <- FALSE tol <- 1e-7 # 10^{-7} while(!conv){ # while not converged.... x0 <- x # save the value before we update x <- x - f(x,P,p,n) / df(x,P,p,n) # make the update conv <- abs(x - x0) < tol # absolute value of change } x # check and see if you found the root of the function: f(x,P,p,n)