# =============================================
# Exercise A - Normal Distribution
# Simpson's 1/3 Rule with n = 4
# =============================================
# Fungsi PDF Standard Normal
f <- function(x) {
1 / sqrt(2 * pi) * exp(-x^2 / 2)
}
# Parameter
a <- 0
b <- 1
n <- 4 # harus genap
h <- (b - a) / n
# Titik-titik x
x <- seq(a, b, length.out = n + 1)
# Hitung f(x) di setiap titik
y <- f(x)
# Simpson's 1/3 Rule
simpson <- (h / 3) * (y[1] + 4 * sum(y[seq(2, n, by = 2)]) + 2 * sum(y[seq(3, n-1, by = 2)]) + y[n+1])
# Hasil
cat("=== HASIL SIMPSON'S 1/3 RULE (n=4) ===\n")
=== HASIL SIMPSON'S 1/3 RULE (n=4) ===
cat("Approksimasi P(0 ≤ X ≤ 1) =", simpson, "\n\n")
Approksimasi P(0 ≤ X ≤ 1) = 0.3413555
# Nilai eksak menggunakan pnorm (untuk perbandingan)
exact <- pnorm(1) - pnorm(0)
cat("Nilai eksak (pnorm(1) - pnorm(0)) =", exact, "\n")
Nilai eksak (pnorm(1) - pnorm(0)) = 0.3413447
cat("Error absolut =", abs(simpson - exact), "\n")
Error absolut = 1.074179e-05
cat("Error relatif (%) =", abs(simpson - exact)/exact * 100, "%\n")
Error relatif (%) = 0.003146903 %
# =============================================
# Exercise B - Exponential Distribution
# Trapezoidal Rule & Simpson's 1/3 Rule (n=10)
# =============================================
# Fungsi PDF Exponential (λ=1)
f <- function(x) {
exp(-x)
}
# Parameter
a <- 0
b <- 2
n <- 10 # harus genap
h <- (b - a) / n
# Titik-titik x dan nilai f(x)
x <- seq(a, b, length.out = n + 1)
y <- f(x)
# ======================
# 1. Trapezoidal Rule
# ======================
trapezoidal <- (h/2) * (y[1] + 2 * sum(y[2:n]) + y[n+1])
# ======================
# 2. Simpson's 1/3 Rule
# ======================
simpson <- (h/3) * (y[1] + 4 * sum(y[seq(2, n, by = 2)]) + 2 * sum(y[seq(3, n-1, by = 2)]) + y[n+1])
# ======================
# Hasil dan Perbandingan
# ======================
exact <- 1 - exp(-2) # nilai eksak dari integral
cat("=== HASIL PERHITUNGAN n = 10 ===\n")
=== HASIL PERHITUNGAN n = 10 ===
cat("Trapezoidal Rule :", trapezoidal, "\n")
Trapezoidal Rule : 0.867545
cat("Simpson's 1/3 Rule :", simpson, "\n")
Simpson's 1/3 Rule : 0.8646724
cat("Nilai Eksak (1 - e^{-2}) :", exact, "\n\n")
Nilai Eksak (1 - e^{-2}) : 0.8646647
cat("Error Trapezoidal :", abs(trapezoidal - exact), "\n")
Error Trapezoidal : 0.002880296
cat("Error Simpson :", abs(simpson - exact), "\n")
Error Simpson : 7.649462e-06
cat("Error relatif Trapezoidal (%):", abs(trapezoidal - exact)/exact * 100, "%\n")
Error relatif Trapezoidal (%): 0.3331113 %
cat("Error relatif Simpson (%) :", abs(simpson - exact)/exact * 100, "%\n")
Error relatif Simpson (%) : 0.0008846738 %
```