##Ejercicio 3.13##  
x  <- 0:4
fx <- c(0.41, 0.37, 0.16, 0.05, 0.01)

Fx <- cumsum(fx)

cdf_tabla <- data.frame(x = x, `f(x)` = fx, `F(x)` = Fx)
cdf_tabla
##   x f.x. F.x.
## 1 0 0.41 0.41
## 2 1 0.37 0.78
## 3 2 0.16 0.94
## 4 3 0.05 0.99
## 5 4 0.01 1.00
##Interpretacion: la probabilidad de que haya como máximo 2 imperfecciones es 𝐹(2)=0.94 F(2)=0.94##

##Grafica##
op <- par(mfrow = c(1,2), mar = c(4.5,4.5,3,1))

barplot(height = fx, names.arg = x,
        main = "PMF: f(x)", xlab = "x", ylab = "Probabilidad")
grid()

plot(x, Fx, type = "s", lwd = 2, ylim = c(0,1),
     main = "CDF: F(x)", xlab = "x", ylab = "Acumulado")
grid()
points(x, Fx, pch = 16)

par(op)
##Ejercicio 3.14##
##Parte a##
lambda <- 8
t <- 12/60   # 12 minutos en horas

F <- function(x) ifelse(x < 0, 0, 1 - exp(-lambda * x))

p_a <- F(t)
p_a
## [1] 0.7981035
##Interpretacion: P(X<12 min)=F(0.2)=1−e−1.6≈0.7981##
##Parte b##
f <- function(x) ifelse(x < 0, 0, lambda * exp(-lambda * x))

p_b <- integrate(f, lower = 0, upper = t)$value
p_b
## [1] 0.7981035
##Interpretacion: P(X<12 min)=∫0 0.2    ​ 8e−8x dx=1−e−1.6≈0.7981##

##Graficas


## 
op <- par(mfrow = c(1,2), mar = c(4.5,4.5,3,1))

# Gráfica de la CDF (parte a)
curve(F, from = 0, to = 1, lwd = 2,
      xlab = "x (horas)", ylab = "F(x)",
      main = "Parte (a): CDF")
grid()
points(t, p_a, pch = 16, col = "red")
segments(0, p_a, t, p_a, lty = 3)
segments(t, 0, t, p_a, lty = 3)

# Gráfica de la PDF (parte b)
curve(f, from = 0, to = 1, lwd = 2,
      xlab = "x (horas)", ylab = "f(x)",
      main = "Parte (b): PDF")
grid()
xs <- seq(0, t, length.out = 300)
polygon(c(0, xs, t), c(0, f(xs), 0),
        col = rgb(0, 0, 1, 0.25), border = NA)
abline(v = t, lty = 3)

par(op)