Created
August 30, 2016 16:23
-
-
Save aschleg/ec184488e0adb14886568b0cda3ce716 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sample function demonstrating how the Newton-Raphson method for root-finding is performed. | |
# Requires the numDeriv package for finding the derivative. One could replace this with the limit using a | |
# small enough h value. | |
# Requires three inputs: | |
# f: univariate function | |
# a: lower bound (also represents starting value for method) | |
# b: upper bound | |
# Newton-Raphson method for finding roots was examined in post here: http://wp.me/p4aZEo-5My | |
newton.raphson <- function(f, a, b, tol = 1e-5, n = 1000) { | |
require(numDeriv) # Package for computing f'(x) | |
x0 <- a # Set start value to supplied lower bound | |
k <- n # Initialize for iteration results | |
# Check the upper and lower bounds to see if approximations result in 0 | |
fa <- f(a) | |
if (fa == 0.0) { | |
return(a) | |
} | |
fb <- f(b) | |
if (fb == 0.0) { | |
return(b) | |
} | |
for (i in 1:n) { | |
dx <- genD(func = f, x = x0)$D[1] # First-order derivative f'(x0) | |
x1 <- x0 - (f(x0) / dx) # Calculate next value x1 | |
k[i] <- x1 # Store x1 | |
# Once the difference between x0 and x1 becomes sufficiently small, output the results. | |
if (abs(x1 - x0) < tol) { | |
root.approx <- tail(k, n=1) | |
res <- list('root approximation' = root.approx, 'iterations' = k) | |
return(res) | |
} | |
# If Newton-Raphson has not yet reached convergence set x1 as x0 and continue | |
x0 <- x1 | |
} | |
print('Too many iterations in method') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment