trapesium <-function(f, a, b, n) {
h <- (b - a) / n
jumlah <- 0
for (i in 1:(n - 1)){
jumlah <- jumlah + f(a + i * h)
}
I <- h / 2 * (f(a) + 2 * jumlah + f(b))
return(I)
}
f<-function(t){2*t^2+1}
trapesium(f,0,6,6)
## [1] 152
turunan_maju <- function(f, x, h) {
(f(x + h) - f(x)) / h
}
turunan_mundur <- function(f, x, h) {
(f(x) - f(x - h)) / h
}
turunan_tengah <- function(f, x, h) {
(f(x + h) - f(x - h)) / (2 * h)
}
turunan_kedua <- function(f, x, h) {
(f(x + h) - 2 * f(x) + f(x - h)) / h^2
}
C <- function(t) { t^3 + 2 * t^2 }
turunan_maju(C, 2, 0.1)
## [1] 20.81
turunan_mundur(C, 2, 0.1)
## [1] 19.21
turunan_tengah(C, 2, 0.1)
## [1] 20.01
turunan_kedua(C, 2, 0.1)
## [1] 16
# Pembanding: turunan simbolik
d1 <- D(expression(t^3 + 2 * t^2), "t")
d1
## 3 * t^2 + 2 * (2 * t)
eval(d1, list(t = 2))
## [1] 20
d2 <- D(d1, "t")
d2
## 3 * (2 * t) + 2 * 2
eval(d2, list(t = 2))
## [1] 16
simpson <- function(f, a, b, n) {
h <- (b - a) / n # lebar pias (n harus genap)
ganjil <- 0
genap <- 0
for (i in 1:(n - 1)) {
if (i %% 2 == 1) {
ganjil <- ganjil + f(a + i * h) # i = 1, 3, 5, ...
} else {
genap <- genap + f(a + i * h) # i = 2, 4, 6, ...
}
}
I <- h / 3 * (f(a) + 4 * ganjil + 2 * genap + f(b))
return(I)
}
C <- function(t) { 10 * t * exp(-0.5 * t) }
simpson(C, 0, 4, 8)
## [1] 23.75731
interpolasi_linear <- function(x, y, x_target) {
if (x_target < min(x) || x_target > max(x)) {
stop("Nilai target berada di luar rentang x")
}
# Cari dua titik x yang mengapit x_target
for (i in 1:(length(x) - 1)) {
if (x[i] <= x_target && x_target <= x[i + 1]) {
# Lakukan interpolasi linier
x1 <- x[i]
x2 <- x[i + 1]
y1 <- y[i]
y2 <- y[i + 1]
# Formula interpolasi linier
y_target <- y1 + (y2 - y1) * ((x_target - x1) / (x2 - x1))
return(y_target)
}
}
}
# Contoh data Z dan probabilitas
z_tabel <- c(-1.96, -1.64, -1.28, 0, 1.28, 1.64, 1.96)
alfa <- c(0.025, 0.05, 0.1, 0.5, 0.9, 0.95, 0.975)
# Target probabilitas yang ingin diinterpolasi
target_alfa <- 0.05
# Panggil fungsi interpolasi linier manual
z_estimate <- interpolasi_linear(alfa, z_tabel, target_alfa)
# Menampilkan hasil
z_estimate
## [1] -1.64