Skip to content

Instantly share code, notes, and snippets.

@kkweon
Created May 25, 2017 04:51
Show Gist options
  • Save kkweon/da899f0ee79e42fdbb56af5917250447 to your computer and use it in GitHub Desktop.
Save kkweon/da899f0ee79e42fdbb56af5917250447 to your computer and use it in GitHub Desktop.
R secant method
library(ggplot2)
secant <- function(fn) {
a <- -100
b <- 100
for (i in 1:1000) {
numerator <- b * fn(a) - a * fn(b)
denominator <- fn(a) - fn(b) + 1e-9
x <- numerator / denominator
a <- b
b <- x
}
x
}
x <- -100:100
fn <- function(x) {
x + x ^ 2
}
temp <- data.frame(x = x, y = fn(x))
ggplot(data = temp, aes(x = x, y = y)) + geom_line() + geom_vline(xintercept = secant(fn),
colour = "red",
linetype = "dashed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment