Skip to content

Instantly share code, notes, and snippets.

@aschleg
Created September 23, 2016 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aschleg/2226c1b255c0f60dadf061e886a14658 to your computer and use it in GitHub Desktop.
Save aschleg/2226c1b255c0f60dadf061e886a14658 to your computer and use it in GitHub Desktop.
Sample function for evaluating a function root using the bisection method.
# Sample function for evaluating a function root using the bisection method
# Inputs required are a function and the starting points to calculate the midpoint
# Function used in post demonstrating the bisection method of root-finding here: http://wp.me/p4aZEo-5MU
bisection <- function(f, a, b, n = 1000, tol = 1e-7) {
# If the signs of the function at the evaluated points, a and b, stop the function and return message.
if (!(f(a) < 0) && (f(b) > 0)) {
stop('signs of f(a) and f(b) differ')
} else if ((f(a) > 0) && (f(b) < 0)) {
stop('signs of f(a) and f(b) differ')
}
for (i in 1:n) {
c <- (a + b) / 2 # Calculate midpoint
# If the function equals 0 at the midpoint or the midpoint is below the desired tolerance, stop the
# function and return the root.
if ((f(c) == 0) || ((b - a) / 2) < tol) {
return(c)
}
# If another iteration is required,
# check the signs of the function at the points c and a and reassign
# a or b accordingly as the midpoint to be used in the next iteration.
ifelse(sign(f(c)) == sign(f(a)),
a <- c,
b <- c)
}
# If the max number of iterations is reached and no root has been found,
# return message and end function.
print('Too many iterations')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment