############################################################################################ # Example: NEWTON-RAPHSON FOR f(x) = x^2 - mu IN THE S LANGUAGE # ############################################################################################ # # # This archive is part of the free distribution of data and statistical software code for # # "Bayesian Methods: A Social and Behavioral Sciences Approach" by Jeff Gill (c) 2002. # # You are free to use, modify, distribute, publish, etc. provided attribution. Please # # forward bugs, complaints, comments, and useful changes to: jgill@ucdavis.edu. # # # ############################################################################################ # # # Self-explanatory. Try different starting points, and different interation numbers. # ############################################################################################ newton.raphson.ex <- function(m,x,iterations) { for (i in 1:iterations) x <- 0.5*(x + m/x) return(x) } # OR, JUST FOR FUN.... secant.ex <- function(m,x,iterations) { for (i in 1:iterations) { x.new <- x[2] - (x[2]^2-m)*(x[2]-x[1])/((x[2]^2-m) - (x[1]^2-m)) x[1] <- x[2]; x[2] <- x.new } return(x[2]) } # > secant.ex(99,c(1,2),8) # [1] 9.949874 # > sqrt(99) # [1] 9.949874