library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
#####################################
#Valor esperado continua
#####################################
a=0
b=1
f0 <- function(x) ifelse(x >= a & x <= b,
(3/14)*(2*x^2 + 2*x + 3), 0)
# Valores para graficar
x0 <- seq(-0.5, 5.5, length.out = 500)
y0 <- f0(x0)
df0 <- data.frame(x = x0, y = y0)
# Gráfico con ggplot2
ggplot(df0, aes(x = x, y = y)) +
geom_line(color = "blue", size = 1.2) +
geom_area(data = subset(df0, y > 0),
fill = "skyblue",
alpha = 0.5) +
labs(title = "f(x) = (3/14)(2x^2 + 2x + 3) en [0,1]",
x = "x", y = "f(x)") +
theme_minimal()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

# ============================
# Cálculos: Área, Media y Varianza
# ============================
# Área bajo la curva
area_total <- integrate(f0, lower = a,
upper = b)$value
cat("Área total bajo la curva =", area_total, "\n")
## Área total bajo la curva = 1
# Media (valor esperado)
f0_media <- function(x) x * f0(x)
media <- integrate(f0_media, lower = a,
upper = b)$value
cat("Media E[X] =", media, "\n")
## Media E[X] = 0.5714286
# E[X^2]
f0_x2 <- function(x) x^2 * f0(x)
esperado_x2 <- integrate(f0_x2, lower = a,
upper = b)$value
# Varianza = E[X^2] - (E[X])^2
varianza <- esperado_x2 - media^2
cat("Varianza Var(X) =", varianza, "\n")
## Varianza Var(X) = 0.08061224
#####################################
# VALOR MEDIO
#####################################
# 1. Definir la función (puedes cambiar esta)
f1 <- function(x) 3*x^2 # <-- aquí puedes cambiar la función
# 2. Definir los límites del intervalo
a <- 1
b <- 10
# 3. Calcular el valor medio de la integral
valor_medio <- integrate(f1, lower = a, upper = b)$value / (b - a)
# 4. Crear puntos para graficar la función
x_vals <- seq(a - 1, b + 1, length.out = 300)
df1 <- data.frame(x = x_vals, y = f1(x_vals))
# 5. Crear gráfico
ggplot(df1, aes(x = x, y = y)) +
geom_line(color = "blue", size = 1.2) + # curva f(x)
geom_area(data = subset(df1, x >= a & x <= b), # área bajo f(x) en [a, b]
aes(x = x, y = y), fill = "skyblue", alpha = 0.4) +
geom_hline(yintercept = valor_medio,
color = "red",
linetype = "dashed",
size = 1) + # valor medio
geom_text(aes(x = (a + b)/2,
y = valor_medio + 1),
label = paste0("f_prom = ", round(valor_medio, 4)),
color = "red", size = 4) +
labs(title = "Función f(x) y su valor medio en [a, b]",
subtitle = paste("Intervalo: [", a, ",", b, "]"),
x = "x", y = "f(x)") +
theme_minimal()
## Warning in geom_text(aes(x = (a + b)/2, y = valor_medio + 1), label = paste0("f_prom = ", : All aesthetics have length 1, but the data has 300 rows.
## ℹ Please consider using `annotate()` or provide this layer with data containing
## a single row.

valor_medio
## [1] 111