Created
September 7, 2016 18:04
-
-
Save aschleg/16dfc0c6f926c4a8e01eafe9925de428 to your computer and use it in GitHub Desktop.
Simple function for performing the secant method of root finding
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
# Simple function for performing the secant method of root finding. | |
# Function takes three arguments: | |
# f: the function in question | |
# x0: first starting value | |
# x1: second starting value | |
# Function used in post on demonstrating the secant method here: http://wp.me/p4aZEo-5MH | |
secant.method <- function(f, x0, x1, tol = 1e-9, n = 500) { | |
if (is.function(f) == FALSE) { | |
stop('f is not a function') | |
} | |
for (i in 1:n) { | |
x2 <- x1 - f(x1) / ((f(x1) - f(x0)) / (x1 - x0)) # Calculate the new x value | |
if (abs(x2 - x1) < tol) { # If the difference between the new value and the previous value is small enough, end iteration and output root. | |
return(x2) | |
} | |
# If the root was not determined in the previous iteration, reassign the values and proceed to next iteration. | |
x0 <- x1 | |
x1 <- x2 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment