########## R script: NewtonRaphson ########## # For using Newton-Raphson iteration to # find a root of an equstion. # Last changed: 15 APR 2019 # Specify function "f" for which root is required: f <- function(x) return(x^3 - 110509) # Specify the derivative of the "f": fd <- function(x) return(3*x^2) # Specify starting value: xOld <- 100 # Perform Newton-Raphson iteractions: converged <- FALSE iterNum <- 0 ; maxIter <- 100 while (!converged) { iterNum <- iterNum + 1 # Update the root according to a Newton-Raphson iteration step: xNew <- xOld - f(xOld)/fd(xOld) if (iterNum>1) cat("Ater ",iterNum," iterations the current root approximation is ",xNew,".\n",sep="") # Check for convergence: relativeError <- abs((xNew/xOld)-1) if (relativeError < 0.0000000000000001) converged <- TRUE # Safeguard against non-convergence: if (iterNum>=maxIter) { converged <- TRUE warning("Newton-Raphson failed to converge after ",maxIter," iterations.\n",sep="") } # Set old root value to current new value: xOld <- xNew } # Report answers assuming successful convergence: if (iterNum