In: Computer Science
ANSWER:
I have provided the properly commented
and indented code so you can easily copy the code as well as check
for correct indentation.
I have provided the output image of the code so you can easily
cross-check for the correct output of the code.
Have a nice and healthy day!!
CODE
# function fixedPoint
fixedPoint <- function(f, xinit, tol = 1e-06, itmax = 10000) {
  # defining variable xold and initializing it with x initial
  xold <- xinit
  # calculating iterations
  itel <- 1
  # repeat loop, returning value when passes tolerance or max iter
  repeat {
    # fetching value of f w.r.t x old and assigning value to xnew
    xnew <- f(xold)
    # xold and new difference passes tolerance, returning value
    if ((max(abs(xold - xnew)) < tol) || (itel == itmax)) {
      # passing xnew and # of iterations
      return(c(xnew,itel))
    }
    # otherwise, initializing xold to xnew and incrementing loop counter
    xold <- xnew
    itel <- itel + 1
  }
}
# a. 1.5*cos(x), xinit = 0.5
# defining function 1.5*cos(x)
fun <- function(x) return(1.5*cos(x))
# accurate sol in first 2 digit
fst2 <- fixedPoint(fun,0.5,1e-02)
# priniting result and iteration
cat("first 2 digits accurate: ",fst2[1],"\nfirst 2 digits accurate iterations: ",fst2[2])
# accurate sol in first 3 digit
fst3 <- fixedPoint(fun,0.5,1e-03)
# priniting result and iteration
cat("first 3 digits accurate: ",fst3[1],"\nfirst 3 digits accurate iterations: ",fst3[2])
# accurate sol in first 4 digit
fst4 <- fixedPoint(fun,0.5,1e-04)
# priniting result and iteration
cat("first 4 digits accurate: ",fst4[1],"\nfirst 4 digits accurate iterations: ",fst4[2])
# starting value to 0.7
# accurate sol for start 0 digit
strt0 <- fixedPoint(fun,0,1e-03)
# priniting result and iteration
cat("start 0, x value: ",strt0[1],"\nstart 0, x iterations: ",strt0[2])
# accurate sol for start 0.7 digit
strt7 <- fixedPoint(fun,0.7,1e-03)
# priniting result and iteration
cat("start 0.7, x value: ",strt7[1],"\nstart 0.7, x iterations: ",strt7[2])
print("Iteration has not converged till now!")
# b for function cos(x)/30 + 44x/45
print("For eqn cos(x)/30 + 44*x/45")
fun <- function(x) return(cos(x)/30 + 44*x/45)
# accurate sol in first 2 digit
fst2 <- fixedPoint(fun,0.5,1e-02)
# priniting result and iteration
cat("first 2 digits accurate: ",fst2[1],"\nfirst 2 digits accurate iterations: ",fst2[2])
print("Iteration converged for this!")
OUTPUT IMAGE
