trapezoid <- function(ftn, a, b, n = 100) {
  h <- (b - a) / n
  x.vec <- seq(a, b, by = h)
  f.vec <- sapply(x.vec, ftn)
  T <- h * (f.vec[1]/2 + sum(f.vec[2:n]) + f.vec[n+1]/2)
  return(T)
}

simpson_n <- function(ftn, a, b, n = 100) {
  # n dipaksa genap dan minimal 4
  n <- max(c(2 * (n %/% 2), 4))
  h <- (b - a) / n
  x.vec1 <- seq(a + h, b - h, by = 2 * h)       # titik ganjil (bobot 4)
  x.vec2 <- seq(a + 2 * h, b - 2 * h, by = 2 * h) # titik genap dalam (bobot 2)
  f.vec1 <- sapply(x.vec1, ftn)
  f.vec2 <- sapply(x.vec2, ftn)
  S <- h / 3 * (ftn(a) + ftn(b) + 4 * sum(f.vec1) + 2 * sum(f.vec2))
  return(S)
}

simpson <- function(ftn, a, b, tol = 1e-8, verbose = FALSE) {
  n <- 4
  h <- (b - a) / 4
  fx <- sapply(seq(a, b, by = h), ftn)
  S <- sum(fx * c(1, 4, 2, 4, 1)) * h / 3
  S.diff <- tol + 1                      # agar perulangan berjalan minimal sekali
  while (S.diff > tol) {
    S.old <- S
    n <- 2 * n
    h <- h / 2
    fx[seq(1, n + 1, by = 2)] <- fx      # pakai kembali nilai f lama
    fx[seq(2, n, by = 2)] <- sapply(seq(a + h, b - h, by = 2 * h), ftn)
    S <- h / 3 * (fx[1] + fx[n + 1] + 4 * sum(fx[seq(2, n, by = 2)]) +
                  2 * sum(fx[seq(3, n - 1, by = 2)]))
    S.diff <- abs(S - S.old)
  }
  if (verbose) cat("partition size", n, "\n")
  return(S)
}

#====================================================
# SOAL 1
#====================================================

f <- function(x){
  sin(x)
}

I <- 2

n <- c(4,8,16,32)

Trap <- sapply(n, function(i)
  trapezoid(f,0,pi,i))

Simp <- sapply(n, function(i)
  simpson_n(f,0,pi,i))

ErrorTrap <- abs(Trap-I)
ErrorSimp <- abs(Simp-I)

RatioTrap <- c(NA,
               ErrorTrap[-length(ErrorTrap)]/
               ErrorTrap[-1])

RatioSimp <- c(NA,
               ErrorSimp[-length(ErrorSimp)]/
               ErrorSimp[-1])

hasil <- data.frame(
  n,
  Trapezoid = Trap,
  ErrorTrap,
  RatioTrap,
  Simpson = Simp,
  ErrorSimp,
  RatioSimp
)

hasil
##    n Trapezoid   ErrorTrap RatioTrap  Simpson    ErrorSimp RatioSimp
## 1  4  1.896119 0.103881102        NA 2.004560 4.559755e-03        NA
## 2  8  1.974232 0.025768398  4.031337 2.000269 2.691699e-04  16.94006
## 3 16  1.993570 0.006429656  4.007741 2.000017 1.659105e-05  16.22381
## 4 32  1.998393 0.001606639  4.001930 2.000001 1.033369e-06  16.05529
#====================================================
# SOAL 2
#====================================================

f <- function(x){
  x*dgamma(x, shape = 3, rate = 2)
}

hasil.simpson <- simpson(f, 0, 20, tol = 1e-8)
hasil.simpson
## [1] 1.5
hasil.integrate <- integrate(f, 0, 20)$value
hasil.integrate
## [1] 1.5
# Nilai harapan teoritis
3/2
## [1] 1.5
#====================================================
# SOAL 3
#====================================================

f <- function(x){
  5*x^4
}

I <- 1

k <- 2:16
eps <- 2^(-k)

n.trap <- numeric(length(eps))
n.simp <- numeric(length(eps))

for(i in 1:length(eps)){
  
  n <- 2
  repeat{
    err <- abs(trapezoid(f,0,1,n)-I)
    if(err <= eps[i]) break
    n <- n+2
  }
  n.trap[i] <- n
  
  n <- 4
  repeat{
    err <- abs(simpson_n(f,0,1,n)-I)
    if(err <= eps[i]) break
    n <- n+2
  }
  n.simp[i] <- n
}

data.frame(
  epsilon = eps,
  n_Trapezoid = n.trap,
  n_Simpson = n.simp
)
##         epsilon n_Trapezoid n_Simpson
## 1  2.500000e-01           4         4
## 2  1.250000e-01           4         4
## 3  6.250000e-02           6         4
## 4  3.125000e-02           8         4
## 5  1.562500e-02          12         4
## 6  7.812500e-03          16         4
## 7  3.906250e-03          22         4
## 8  1.953125e-03          30         6
## 9  9.765625e-04          42         6
## 10 4.882812e-04          60         8
## 11 2.441406e-04          84         8
## 12 1.220703e-04         118        10
## 13 6.103516e-05         166        12
## 14 3.051758e-05         234        14
## 15 1.525879e-05         332        16
plot(eps, n.trap,
     log = "x",
     type = "b",
     col = "red",
     ylim = range(c(n.trap, n.simp)),
     xlab = expression(epsilon),
     ylab = "Jumlah Partisi (n)")

lines(eps, n.simp,
      type = "b",
      col = "blue")

legend("topleft",
       legend = c("Trapezoid", "Simpson"),
       col = c("red", "blue"),
       lty = 1,
       pch = 1)

#====================================================
# SOAL 4
#====================================================

set.seed(2026)

pos <- rnorm(100, 1, 1)
neg <- rnorm(100, 0, 1)

score <- c(pos, neg)
label <- c(rep(1, 100), rep(0, 100))

library(pROC)
## Warning: package 'pROC' was built under R version 4.5.3
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
roc.obj <- roc(label, score)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
auc.pROC <- auc(roc.obj)
auc.pROC
## Area under the curve: 0.7127
# Perbandingan dengan peluang P(skor+ > skor-)
p <- mean(outer(pos, neg, ">"))
p
## [1] 0.7127
plot(roc.obj)