# Definition der Funktion f(x)
f <- function(x) {
  return(16 - x^2)
}

# Zielfunktion für den Flächeninhalt A(x) = 2x * f(x)
# Bereich: x muss zwischen 0 und 4 liegen (Nullstelle)
area_function <- function(x) {
  width <- 2 * x
  height <- f(x)
  return(width * height)
}

# Numerische Optimierung (Maximierung)
# optimize sucht standardmäßig das Minimum, daher maximieren wir mit maximum=TRUE
opt_result <- optimize(area_function, interval = c(0, 4), maximum = TRUE)

x_opt <- opt_result$maximum
max_area <- opt_result$objective
y_opt <- f(x_opt)

# Ausgabe der Ergebnisse
cat("Optimale x-Koordinate (positive Seite):", round(x_opt, 4), "\n")
## Optimale x-Koordinate (positive Seite): 2.3094
cat("Zugehörige y-Koordinate (Höhe):", round(y_opt, 4), "\n")
## Zugehörige y-Koordinate (Höhe): 10.6667
cat("Maximaler Flächeninhalt:", round(max_area, 4), "\n")
## Maximaler Flächeninhalt: 49.2672
# Analytische Werte zur Kontrolle
x_analytic <- 4 / sqrt(3)
cat("\nAnalytischer Wert für x:", round(x_analytic, 4), "\n")
## 
## Analytischer Wert für x: 2.3094
# Erstellen eines Vektors für x-Werte zur Darstellung der Parabel
x_vals <- seq(-4.5, 4.5, length.out = 200)
y_vals <- f(x_vals)

# Plot initialisieren
plot(x_vals, y_vals, type = "l", lwd = 2, col = "blue", 
     main = "Maximales Rechteck unter f(x) = 16 - x^2",
     xlab = "x", ylab = "y", ylim = c(0, 17))

# x-Achse einzeichnen
abline(h = 0, col = "black")
abline(v = 0, col = "gray", lty = 2) # y-Achse als Hilfslinie

# Das maximale Rechteck einzeichnen
# Eckpunkte: (-x_opt, 0), (x_opt, 0), (x_opt, y_opt), (-x_opt, y_opt)
rect_x_left <- -x_opt
rect_y_bottom <- 0
rect_x_right <- x_opt
rect_y_top <- y_opt

# Rechteck zeichnen
rect(rect_x_left, rect_y_bottom, rect_x_right, rect_y_top, 
     border = "red", lwd = 2, col = rgb(1, 0, 0, 0.2)) # Transparent rot gefüllt

# Eckpunkte markieren
points(c(rect_x_left, rect_x_right), c(rect_y_top, rect_y_top), pch = 19, col = "red")
points(c(rect_x_left, rect_x_right), c(rect_y_bottom, rect_y_bottom), pch = 19, col = "red")

# Beschriftung der Eckpunkte
text(rect_x_right, rect_y_top + 1, labels = paste0("(", round(x_opt, 2), "|", round(y_opt, 2), ")"), pos = 4, col = "red")
text(rect_x_right, rect_y_bottom - 1, labels = paste0("(", round(x_opt, 2), "|0)"), pos = 4, col = "red")

# Scheitelpunkt markieren
points(0, 16, pch = 19, col = "blue")
text(0, 16.5, labels = "S(0|16)", pos = 3)

# Nullstellen markieren
points(c(-4, 4), c(0, 0), pch = 19, col = "blue")
text(-4, -1, labels = "-4", pos = 3)
text(4, -1, labels = "4", pos = 3)

# Legende
legend("topright", legend = c("f(x) = 16 - x^2", "Maximales Rechteck"), 
       col = c("blue", "red"), lwd = 2, fill = c(NA, rgb(1, 0, 0, 0.2)), border = c(NA, "red"))