newtonraphson <- function(ftn, x0, tol = 1e-9, max.iter = 100) {
  # Algoritma Newton-Raphson untuk menyelesaikan ftn(x)[1] == 0
  # ftn adalah fungsi satu variabel yang mengembalikan vektor berpanjang 2:
  #   nilai fungsi f(x) dan turunan pertamanya f'(x)
  # x0 adalah tebakan awal akar.
  # Algoritma berhenti ketika |f(x)| <= tol, atau iterasi melebihi max.iter.

  # inisialisasi
  x <- x0
  fx <- ftn(x)
  iter <- 0

  # ulangi sampai kondisi berhenti terpenuhi
  while ((abs(fx[1]) > tol) && (iter < max.iter)) {
    x <- x - fx[1] / fx[2]
    fx <- ftn(x)
    iter <- iter + 1
    cat("At iteration", iter, "value of x is:", x, "\n")
  }

  # keluaran bergantung pada keberhasilan algoritma
  if (abs(fx[1]) > tol) {
    cat("Algorithm failed to converge\n")
    return(NULL)
  } else {
    cat("Algorithm converged\n")
    return(x)
  }
}

secant <- function(ftn, x0, x1, tol = 1e-9, max.iter = 100) {
  f0 <- ftn(x0)
  f1 <- ftn(x1)
  iter <- 0
  while ((abs(f1) > tol) && (iter < max.iter)) {
    if (f1 == f0) {                       # garis sekan mendatar: tidak memotong sumbu-x
      cat("error: f(x_i) = f(x_{i-1}), pembagi nol\n")
      return(NULL)
    }
    x2 <- x1 - f1 * (x1 - x0) / (f1 - f0)
    x0 <- x1; f0 <- f1                    # geser: titik baru menjadi x_i
    x1 <- x2; f1 <- ftn(x1)
    iter <- iter + 1
    cat("At iteration", iter, "value of x is:", x1, "\n")
  }
  if (abs(f1) > tol) {
    cat("Algorithm failed to converge\n")
    return(NULL)
  } else {
    cat("Algorithm converged\n")
    return(x1)
  }
}

newton_aman <- function(ftn, lo, hi, tol = 1e-10, max.iter = 100) {
  # Bila langkah Newton keluar dari [lo, hi] atau f'(x) = 0, diganti titik tengah
  flo <- ftn(lo)[1]; fhi <- ftn(hi)[1]
  if (flo * fhi > 0) stop("akar tidak terkurung pada [lo, hi]")
  x <- (lo + hi) / 2
  for (iter in 1:max.iter) {
    fx <- ftn(x)
    if (abs(fx[1]) < tol) return(list(root = x, iter = iter - 1))
    if (flo * fx[1] < 0) hi <- x else lo <- x
    xn <- if (fx[2] != 0) x - fx[1] / fx[2] else NA
    x <- if (!is.na(xn) && xn > lo && xn < hi) xn else (lo + hi) / 2
  }
  stop("batas iterasi tercapai")
}

# No.1 Tentukan akar f(x) = x³ − x − 2 dengan x0 = 1,5 dan tol 10^-10. Bandingkan jumlah iterasi dengan Bisection pada [1, 2] dan dengan uniroot.
f1 <- function(x) {
  c(x^3 - x - 2, 3*x^2 - 1)
}

#Newton-Raphson
hasil_newton <- newtonraphson(f1, 1.5, tol = 1e-10)
## At iteration 1 value of x is: 1.521739 
## At iteration 2 value of x is: 1.52138 
## At iteration 3 value of x is: 1.52138 
## Algorithm converged
hasil_newton
## [1] 1.52138
# Bandingkan dengan bisection dan uniroot
f <- function(x) x^3 - x - 2

#Bisection manual
a <- 1
b <- 2
iter <- 0
tol <- 1e-10

while (abs(f((a+b)/2)) > tol) {
  tengah <- (a+b)/2

  if (f(a)*f(tengah) < 0) {
    b <- tengah
  } else {
    a <- tengah
  }

  iter <- iter + 1
}

akar_bisection <- (a+b)/2

#uniroot
hasil_uniroot <- uniroot(f, c(1,2), tol = 1e-10)

akar_bisection
## [1] 1.52138
iter
## [1] 32
hasil_uniroot$root
## [1] 1.52138
hasil_uniroot$iter
## [1] 8

Interpretasi:

Berdasarkan hasil perhitungan, metode Newton-Raphson memperoleh akar persamaan sebesar 1,5213797068 dengan 3 iterasi. Sementara itu, metode Bisection memperoleh akar yang mendekati nilai tersebut dengan 32 iterasi. Fungsi uniroot() juga menghasilkan akar yang mendekati kedua metode tersebut dengan 8 iterasi. Dari hasil tersebut, Newton-Raphson membutuhkan jumlah iterasi paling sedikit, diikuti oleh uniroot() dan Bisection. Hal ini menunjukkan bahwa Newton-Raphson lebih cepat mencapai akar pada permasalahan ini berdasarkan jumlah iterasinya.

# No.2 Cari t0,975 untuk df = 9 dengan Newton (f = pt(x, 9) − 0,975, f′ = dt(x, 9)), bandingkan dengan qt(0.975,9). Coba x0 = 10 dan jelaskan hasilnya.
ft <- function(x) {
  c(pt(x, 9) - 0.975, dt(x, 9))
}

#Newton-Raphson dengan x0 = 1
hasil_t <- newtonraphson(ft, 1, tol = 1e-10)
## At iteration 1 value of x is: 1.640325 
## At iteration 2 value of x is: 2.047073 
## At iteration 3 value of x is: 2.229612 
## At iteration 4 value of x is: 2.261325 
## At iteration 5 value of x is: 2.262157 
## At iteration 6 value of x is: 2.262157 
## Algorithm converged
#Pembanding
qt(0.975, 9)
## [1] 2.262157
#Percobaan dengan x0 = 10
hasil_t10 <- tryCatch(
  newtonraphson(ft, 10, tol = 1e-10),
  error = function(e) e$message
)
## At iteration 1 value of x is: -16776.42 
## At iteration 2 value of x is: 7.514743e+37 
## At iteration 3 value of x is: -Inf 
## At iteration 4 value of x is: NaN
hasil_t10
## [1] "missing value where TRUE/FALSE needed"

Interpretasi:

Dengan nilai awal (x0=1), metode Newton-Raphson memperoleh hasil sebesar 2,2621571628 dengan 6 iterasi. Hasil tersebut mendekati nilai dari fungsi qt(0.975, 9). Namun, ketika menggunakan nilai awal (x0=10), metode tidak berhasil mencapai akar karena nilai turunannya sangat kecil sehingga perubahan iterasi menjadi sangat besar. Hal ini menunjukkan bahwa pemilihan nilai awal berpengaruh terhadap keberhasilan metode Newton-Raphson.

# No.3 Selesaikan cos x = x dengan Secant (x0 = 0, x1 = 1) dan Newton (x0 = 1). Bandingkan iterasi dan jumlah evaluasi fungsi.
f3 <- function(x) {
  cos(x) - x
}

#Turunan
df3 <- function(x) {
  -sin(x) - 1
}

#Newton-Raphson
ftn3 <- function(x) {
  c(f3(x), df3(x))
}

hasil_newton3 <- newtonraphson(
  ftn3, 1, tol = 1e-10
)
## At iteration 1 value of x is: 0.7503639 
## At iteration 2 value of x is: 0.7391129 
## At iteration 3 value of x is: 0.7390851 
## At iteration 4 value of x is: 0.7390851 
## Algorithm converged
#Secant
hasil_secant3 <- secant(
  f3, 0, 1, tol = 1e-10
)
## At iteration 1 value of x is: 0.6850734 
## At iteration 2 value of x is: 0.736299 
## At iteration 3 value of x is: 0.7391194 
## At iteration 4 value of x is: 0.7390851 
## At iteration 5 value of x is: 0.7390851 
## Algorithm converged
#Menampilkan hasil
hasil_newton3
## [1] 0.7390851
hasil_secant3
## [1] 0.7390851
#Jumlah evaluasi fungsi
evaluasi_newton <- 5
evaluasi_secant <- 7

#Menampilkan hasil
evaluasi_newton
## [1] 5
evaluasi_secant
## [1] 7

Interpretasi:

Metode Newton-Raphson dan Secant menghasilkan akar persamaan yang mendekati 0,7390851332. Newton-Raphson membutuhkan 4 iterasi, sedangkan Secant membutuhkan 5 iterasi. Jumlah evaluasi fungsi pada Newton-Raphson sebanyak 5 kali, sedangkan Secant sebanyak 7 kali. Newton-Raphson menggunakan turunan fungsi, sementara Secant tidak memerlukan turunan tetapi membutuhkan dua nilai awal.

# No.4 Taksir MLE parameter bentuk Gamma (α) dari data Anda dengan Newton (rumus di bawah, f′ = 1/α − trigamma(α)), α0 = 1/(2s). Bandingkan dengan MASS::fitdistr.

data_dummy <- c(2.3, 1.8, 3.1, 2.7, 1.5, 4.0, 2.2, 3.5, 2.9, 1.9)

# Menghitung nilai s
s <- log(mean(data_dummy)) - mean(log(data_dummy))

# Nilai awal alpha
alpha0 <- 1 / (2*s)

# Fungsi dan turunan pertama
f_gamma <- function(alpha) {
  c(
    log(alpha) - digamma(alpha) - s,
    1/alpha - trigamma(alpha)
  )
}

# Estimasi alpha menggunakan Newton-Raphson
hasil_gamma <- newtonraphson(
  f_gamma, alpha0, tol = 1e-10
)
## At iteration 1 value of x is: 11.74442 
## At iteration 2 value of x is: 11.74675 
## At iteration 3 value of x is: 11.74675 
## Algorithm converged
# Menampilkan hasil
hasil_gamma
## [1] 11.74675
# Pembanding menggunakan fitdistr
library(MASS)
## Warning: package 'MASS' was built under R version 4.5.3
hasil_fit <- fitdistr(data_dummy, "gamma")
hasil_fit
##      shape       rate   
##   11.746726    4.535417 
##  ( 5.180379) ( 2.043451)

Interpretasi

Berdasarkan hasil perhitungan menggunakan data dummy, metode Newton-Raphson memperoleh estimasi parameter shape distribusi Gamma sebesar 11,74675 dengan 3 iterasi hingga algoritma konvergen. Sementara itu, fungsi fitdistr() dari package MASS menghasilkan estimasi parameter shape sebesar 11,746726 dan parameter rate sebesar 4,535417. Kedua metode menghasilkan estimasi parameter shape yang hampir sama. Hal ini menunjukkan bahwa metode Newton-Raphson mampu memberikan hasil estimasi yang mendekati hasil dari fungsi fitdistr().