Skip to content

Instantly share code, notes, and snippets.

@wibeasley
Created February 9, 2020 05:57
Show Gist options
  • Save wibeasley/faf0c1ca52bf860b112cf0dab708475a to your computer and use it in GitHub Desktop.
Save wibeasley/faf0c1ca52bf860b112cf0dab708475a to your computer and use it in GitHub Desktop.
Finding & graphing the intersection between two lines
f1 <- function(x) (3*x - 40) / 10
f2 <- function(x) (-20 - 2*x) / 2
# f1 <- function(x) (24000 - 200*x) / 350
# f2 <- function(x) (130 - x) / 2
x_limits <- c(-10, 100)
########## Don't change anything below this line #########################
g <- function(x) f1(x) - f2(x)
y_range <- range(0, f1(x_limits), f2(x_limits))
x_midpoint <- mean(x_limits)
y_midpoint <- mean(y_range)
plot(x=NA, y=NA, xlim = x_limits, ylim = y_range, xlab = "x", ylab = "y")
abline(v = 0, col = "gray70")
abline(h = 0, col = "gray70")
curve(f1, add = T, col = "blue")
curve(f2, add = T, col = "tomato")
root <- uniroot(g, lower = x_limits[1], upper = x_limits[2])
x <- root$root
y <- f1(root$root)
root
abline(v = x, col = "green3", lty=2)
abline(h = y, col = "green3", lty=2)
if(x < x_midpoint) {
text(labels=sprintf("y = %f\n", y), x=x_limits[2], y=y, adj = 1, col = "green3")
} else {
text(labels=sprintf("y = %f\n", y), x=x_limits[1], y=y, adj = 0, col = "green3")
}
if(y < y_midpoint) {
text(labels=sprintf("x = %f", x), x=x, y=y_range[2], adj = 0, col = "green3")
} else {
text(labels=sprintf("x = %f", x), x=x, y=y_range[1], adj = 0, col = "green3")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment