Trapezoidal dan Simpson Hitung ∫0 π sin x dx = 2 dengan n = 4, 8, 16, 32. Tabelkan galat dan rasio antar-n; apakah mendekati 4 dan 16?

# Mendefinisikan fungsi
f <- function(x) sin(x)

# Metode Trapesium Komposit
trapezoid <- function(f, a, b, n) {
  h <- (b - a) / n
  x <- seq(a, b, length.out = n + 1)
  y <- f(x)
  
  h * (
    y[1] / 2 +
      sum(y[2:n]) +
      y[n + 1] / 2
  )
}

# Metode Simpson Komposit
simpson_comp <- function(f, a, b, n) {
  if (n %% 2 != 0) {
    stop("n harus genap untuk metode Simpson.")
  }
  
  h <- (b - a) / n
  x <- seq(a, b, length.out = n + 1)
  y <- f(x)
  
  h / 3 * (
    y[1] + y[n + 1] +
      4 * sum(y[seq(2, n, by = 2)]) +
      2 * sum(y[seq(3, n - 1, by = 2)])
  )
}

# Nilai integral eksak
nilai_eksak <- 2

# Jumlah subinterval
n <- c(4, 8, 16, 32)

# Menghitung hasil integrasi
hasil_trap <- sapply(
  n,
  function(k) trapezoid(f, 0, pi, k)
)

hasil_simp <- sapply(
  n,
  function(k) simpson_comp(f, 0, pi, k)
)

# Menghitung galat
galat_trap <- abs(hasil_trap - nilai_eksak)
galat_simp <- abs(hasil_simp - nilai_eksak)

# Menghitung rasio galat
rasio_trap <- c(
  NA,
  galat_trap[-length(galat_trap)] / galat_trap[-1]
)

rasio_simp <- c(
  NA,
  galat_simp[-length(galat_simp)] / galat_simp[-1]
)

# Membuat tabel hasil
data.frame(
  n = n,
  Trapesium = hasil_trap,
  Galat_Trapesium = galat_trap,
  Rasio_Galat_Trapesium = rasio_trap,
  Simpson = hasil_simp,
  Galat_Simpson = galat_simp,
  Rasio_Galat_Simpson = rasio_simp
)
##    n Trapesium Galat_Trapesium Rasio_Galat_Trapesium  Simpson Galat_Simpson
## 1  4  1.896119     0.103881102                    NA 2.004560  4.559755e-03
## 2  8  1.974232     0.025768398              4.031337 2.000269  2.691699e-04
## 3 16  1.993570     0.006429656              4.007741 2.000017  1.659105e-05
## 4 32  1.998393     0.001606639              4.001930 2.000001  1.033369e-06
##   Rasio_Galat_Simpson
## 1                  NA
## 2            16.94006
## 3            16.22381
## 4            16.05529

Interpretasi: Ketiga metode menghasilkan akar yang sama, yaitu x ≈ 1,5213797. Newton-Raphson konvergen kuadratik: jumlah digit benar kira-kira berlipat dua tiap iterasi, sehingga cukup sekitar 3–4 iterasi dari x₀ = 1,5. Bisection hanya konvergen linear (galat dibagi dua tiap iterasi) sehingga butuh sekitar 34 iterasi untuk tol 10⁻¹⁰ pada [1, 2]. uniroot memakai metode Brent (gabungan bisection, secant, dan interpolasi), jadi jumlah iterasinya biasanya di antara keduanya. Newton unggul dalam jumlah iterasi, tetapi perlu turunan f′ dan tebakan awal yang baik.

  1. Nilai harapan Untuk X ~ Gamma(shape = 3, rate = 2), hitung E(X) = ∫ x f(x) dx dengan simpson() pada [0, 20] (tol 10−8), lalu bandingkan dengan 1,5 dan integrate()..
simpson_comp <- function(f, a, b, n) {
  if (n %% 2 != 0) stop("n harus genap")
  h <- (b - a) / n
  x <- seq(a, b, length.out = n + 1)
  y <- f(x)
  idx <- 2:n                              
  koef <- ifelse(idx %% 2 == 0, 4, 2)    
  (h / 3) * (y[1] + y[n + 1] + sum(koef * y[idx]))
}
f_gamma <- function(x) dgamma(x, shape = 3, rate = 2)

integran <- function(x) x * f_gamma(x)

simpson <- function(f, a, b, tol = 1e-8, max.iter = 20) {
  n <- 2
  S_lama <- simpson_comp(f, a, b, n)
  
  for (iter in 1:max.iter) {
    n <- 2 * n
    S_baru <- simpson_comp(f, a, b, n)
    galat <- abs(S_baru - S_lama) / 15
    
    if (galat < tol) {
      return(list(integral = S_baru, galat = galat,
                  n = n, iterasi = iter))
    }
    S_lama <- S_baru
  }
  
  warning("Toleransi belum tercapai.")
  list(integral = S_baru, galat = galat, n = n, iterasi = max.iter)
}

hasil_simpson <- simpson(integran, a = 0, b = 20, tol = 1e-8)
hasil_simpson
## $integral
## [1] 1.5
## 
## $galat
## [1] 1.210348e-09
## 
## $n
## [1] 2048
## 
## $iterasi
## [1] 10
hasil_integrate <- integrate(integran, lower = 0, upper = 20)
hasil_integrate
## 1.5 with absolute error < 6.3e-10
nilai_teoritis <- 3 / 2
nilai_teoritis
## [1] 1.5
data.frame(
  Metode    = c("Simpson", "integrate()", "Teoritis"),
  Nilai_E_X = c(hasil_simpson$integral,
                hasil_integrate$value,
                nilai_teoritis)
)
##        Metode Nilai_E_X
## 1     Simpson       1.5
## 2 integrate()       1.5
## 3    Teoritis       1.5

Interpretasi: Dari tebakan awal yang dekat (misalnya x₀ = 2), Newton konvergen cepat ke 2,262157, sama dengan qt(0.975, 9). Dari x₀ = 10, Newton bermasalah. Di sana kurva CDF sudah hampir datar (pt ≈ 1) dan f′ = dt(10, 9) sangat kecil, sehingga langkah f/f′ menjadi sangat besar dan titik berikutnya terlempar jauh dari akar. Iterasi bisa melompat ke ekor lain yang f′-nya hampir nol, lalu menjadi tidak stabil, menghasilkan NaN/Inf atau divergen. Pelajarannya, Newton hanya konvergen lokal dan sensitif terhadap tebakan awal, terutama untuk fungsi berbentuk sigmoid seperti CDF. Solusinya memakai tebakan awal yang dekat atau metode yang aman seperti bisection/uniroot.

  1. Memilih n Untuk ∫0 1 5x⁴ dx, cari nT (ε) dan nS (ε) terkecil agar galat ≤ ε = 2−k, k = 2, …, 16. Plot terhadap ε (skala log)
f <- function(x) 5 * x^4
nilai_eksak <- 1

cari_n_trap <- function(epsilon, max_n = 1000000) {
  n <- 1
  while (n <= max_n) {
    galat <- abs(trapezoid(f, 0, 1, n) - nilai_eksak)
    if (galat <= epsilon) return(n)
    n <- n + 1
  }
  NA
}

cari_n_simp <- function(epsilon, max_n = 1000000) {
  n <- 2
  while (n <= max_n) {
    galat <- abs(simpson_comp(f, 0, 1, n) - nilai_eksak)
    if (galat <= epsilon) return(n)
    n <- n + 2
  }
  NA
}

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

n_trap <- sapply(epsilon, cari_n_trap)
n_simp <- sapply(epsilon, cari_n_simp)

hasil_n <- data.frame(
  k = k,
  epsilon = epsilon,
  n_Trapesium = n_trap,
  n_Simpson = n_simp
)
hasil_n
##     k      epsilon n_Trapesium n_Simpson
## 1   2 2.500000e-01           3         2
## 2   3 1.250000e-01           4         2
## 3   4 6.250000e-02           6         2
## 4   5 3.125000e-02           8         4
## 5   6 1.562500e-02          11         4
## 6   7 7.812500e-03          15         4
## 7   8 3.906250e-03          21         4
## 8   9 1.953125e-03          30         6
## 9  10 9.765625e-04          42         6
## 10 11 4.882812e-04          59         8
## 11 12 2.441406e-04          83         8
## 12 13 1.220703e-04         117        10
## 13 14 6.103516e-05         166        12
## 14 15 3.051758e-05         234        14
## 15 16 1.525879e-05         331        16
plot(
  epsilon, n_trap,
  type = "b", log = "xy",
  ylim = range(c(n_trap, n_simp), na.rm = TRUE),
  xlab = expression(epsilon),
  ylab = "Jumlah subinterval minimum (n)",
  main = "Perbandingan Jumlah Subinterval Minimum"
)

lines(epsilon, n_simp, type = "b", lty = 2, pch = 2)

legend(
  "topright",
  legend = c("Trapesium", "Simpson"),
  lty = c(1, 2),
  pch = c(1, 2)
)

Interpretasi: Kedua metode menemukan akar x ≈ 0,7390851. Newton biasanya butuh iterasi sedikit lebih sedikit (orde konvergensi 2) dibanding Secant (orde ≈ 1,618). Namun setiap iterasi Newton memerlukan 2 evaluasi (f dan f′), sedangkan Secant hanya 1 evaluasi f per iterasi. Akibatnya total evaluasi fungsi Secant sering sama atau lebih sedikit, dan Secant tidak memerlukan turunan. Jadi Secant lebih efisien per evaluasi, sedangkan Newton lebih efisien per iterasi.

  1. Proyek mini: AUC ROC Bangkitkan skor 100 kasus positif N(1, 1) dan 100 negatif N(0, 1) (set.seed(2026)). Hitung AUC kurva ROC dengan Trapezoidal dan bandingkan dengan P(skor⁺ > skor⁻).
#soal 4
# Membangkitkan data skor
set.seed(2026)

skor_positif <- rnorm(100, mean = 1, sd = 1)
skor_negatif <- rnorm(100, mean = 0, sd = 1)

# Menentukan threshold
threshold <- c(
  Inf,
  sort(
    unique(c(skor_positif, skor_negatif)),
    decreasing = TRUE
  ),
  -Inf
)

# Menghitung True Positive Rate
TPR <- sapply(
  threshold,
  function(t) mean(skor_positif >= t)
)

# Menghitung False Positive Rate
FPR <- sapply(
  threshold,
  function(t) mean(skor_negatif >= t)
)

# Mengurutkan FPR
urutan <- order(FPR)

FPR <- FPR[urutan]
TPR <- TPR[urutan]

# Menghitung AUC menggunakan metode Trapesium
AUC_trapesium <- sum(
  diff(FPR) *
    (TPR[-1] + TPR[-length(TPR)]) / 2
)

AUC_trapesium

# Menghitung peluang empiris P(score+ > score-)
prob_empiris <- mean(
  outer(skor_positif, skor_negatif, ">")
)

prob_empiris

# Membandingkan kedua hasil
data.frame(
  Metode = c("AUC Trapesium", "Peluang empiris"),
  Nilai = c(
    AUC_trapesium,
    prob_empiris
  )
)

# Membuat kurva ROC
plot(
  FPR,
  TPR,
  type = "l",
  xlab = "False Positive Rate",
  ylab = "True Positive Rate",
  main = "Kurva ROC"
)

abline(0, 1, lty = 2)

Interpretasi: Persamaan f(α) = ln α − ψ(α) − s = 0 tidak punya solusi tertutup, sehingga dicari secara numerik dengan Newton. Tebakan awal α₀ = 1/(2s) berasal dari pendekatan ψ(α) ≈ ln α − 1/(2α), yang sudah dekat dengan akar, sehingga Newton konvergen dalam beberapa iterasi saja. Estimasi α dari Newton hampir identik dengan shape dari fitdistr, karena keduanya memaksimumkan likelihood yang sama. Perbedaan sangat kecil hanya karena toleransi optimasi fitdistr. Nilainya juga mendekati α sebenarnya (3) dan semakin dekat jika n besar.

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.