library(ggplot2)
library(pracma)
We want to calculate the total area enclosed by the following functions:
\[f(x) = 2x^2 + 5x - 3\]
\[g(x) = x^2 + 4x - 1\]
f <- function(x) { 2 * x^2 + 5 * x - 3 }
g <- function(x) { x^2 + 4 * x - 1 }
To find the areas enclosed by the curves, we first need to determine where they intersect.
intersection <- function(x) {
f(x) - g(x)
}
# Using a numerical method to find roots
x1 <- uniroot(intersection, c(-10, 0))$root
x2 <- uniroot(intersection, c(0, 10))$root
c(x1, x2)
## [1] -2.0000050 0.9999746
# Integrating the absolute difference of f and g between the roots
total_area <- integrate(Vectorize(function(x) abs(f(x) - g(x))), x1, x2)$value
total_area
## [1] 4.5
df <- data.frame(x = seq(x1, x2, length.out = 100))
df$yf <- f(df$x)
df$yg <- g(df$x)
ggplot(df, aes(x)) +
geom_line(aes(y = yf, colour = "f(x)")) +
geom_line(aes(y = yg, colour = "g(x)")) +
geom_ribbon(aes(ymin = pmin(yf, yg), ymax = pmax(yf, yg)), fill = "blue", alpha = 0.3) +
labs(title = "Area between f(x) and g(x)", x = "x", y = "y") +
scale_colour_manual("", values = c("f(x)" = "red", "g(x)" = "green")) +
theme_minimal()