Reputation: 323
I have 2 functions and I would like to find the values at which their intersect and plot it on the graph. How can I best achieve this? Does anyone know an R function for that?
# First Function
func6 <- function(x)
{
x * log(x) - sqrt(x)
}
# Second Function
func7 <- function(x)
{
x
}
x <- seq(0,10,length=100)
plot(x, func6(x), col="blue", lwd="1", main="Graph #1")
lines(x, func7(x), col="red")
Upvotes: 1
Views: 5757
Reputation: 25854
You can use uniroot
to search for the intersection; this equates to searching for the zero of the difference of the functions.
rt <- uniroot(function(x) func6(x) - func7(x) , c(.01,10), tol=1e-8)
# or explicitly
# rt <- uniroot(function(x) x * log(x) - sqrt(x) - x , c(.01,10), tol=1e-8)
# check
all.equal(func6(rt$root), func7(rt$root))
# [1] TRUE
Then plot it
x <- seq(0, 10, length=100)
plot(x, func6(x), col="blue", lwd="1", main="Graph #1", type="l")
lines(x, func7(x), col="red")
points(rt$root, rt$root, pch=16, cex=2, col="red")
As pointed out by K.Troy, in the general case the y-coordinate should be transformed : "The second argument to the points function should be to invoke either func6 or func7 using rt$root"
points(rt$root, func6(rt$root), pch=16, cex=2, col="red")
Upvotes: 1