# Tugas Mandiri 
# Rendi Ramadani (3338250041)
newtonraphson <- function(ftn, x0, tol = 1e-9, max.iter = 100) {
  x <- x0
  fx <- ftn(x)
  iter <- 0
  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")
  }
  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) {
      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
    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) {
  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")
}

# Fungsi Bisection standar sebagai pembanding di Nomor 1
bisection <- function(ftn, a, b, tol = 1e-10) {
  fa <- ftn(a); fb <- ftn(b)
  if (fa * fb > 0) stop("Akar tidak terkurung")
  iter <- 0
  while ((b - a) / 2 > tol) {
    c <- (a + b) / 2
    fc <- ftn(c)
    iter <- iter + 1
    if (fc == 0) break
    if (fa * fc < 0) { b <- c; fb <- fc } else { a <- c; fa <- fc }
  }
  return(list(root = (a + b) / 2, iter = iter))
}

# 1. NEWTON-RAPHSON
f1 <- function(x) c(x^3 - x - 2, 3*x^2 - 1)

akar_nr1 <- newtonraphson(f1, x0 = 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
akar_bis <- bisection(function(x) f1(x)[1], a = 1, b = 2, tol = 1e-10)
akar_uni <- uniroot(function(x) f1(x)[1], interval = c(1, 2), tol = 1e-10)

cat("Akar Newton-Raphson:", format(akar_nr1, digits = 12), "\n")
## Akar Newton-Raphson: 1.5213797068
cat("Bisection [1, 2] -> Akar:", format(akar_bis$root, digits = 12), "| Iterasi:", akar_bis$iter, "\n")
## Bisection [1, 2] -> Akar: 1.52137970686 | Iterasi: 33
cat("uniroot [1, 2]   -> Akar:", format(akar_uni$root, digits = 12), "| Iterasi:", akar_uni$iter, "\n")
## uniroot [1, 2]   -> Akar: 1.5213797068 | Iterasi: 8
# 2. KUANTIL t 
ft <- function(x) c(pt(x, df = 9) - 0.975, dt(x, df = 9))

# Dengan tebakan awal wajar (misal x0 = 2)
akar_t <- newtonraphson(ft, x0 = 2, tol = 1e-10)
## At iteration 1 value of x is: 2.215137 
## At iteration 2 value of x is: 2.260436 
## At iteration 3 value of x is: 2.262155 
## At iteration 4 value of x is: 2.262157 
## Algorithm converged
cat("Hasil Newton (x0 = 2):", format(akar_t, digits = 10), "\n")
## Hasil Newton (x0 = 2): 2.262157163
cat("Pembanding qt(0.975, 9):", format(qt(0.975, 9), digits = 10), "\n")
## Pembanding qt(0.975, 9): 2.262157163
# Mencoba tebakan awal ekstrem x0 = 10
cat("\nMencoba x0 = 10 pada Newton murni:\n")
## 
## Mencoba x0 = 10 pada Newton murni:
try(newtonraphson(ft, x0 = 10, tol = 1e-10))
## 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 
## Error in while ((abs(fx[1]) > tol) && (iter < max.iter)) { : 
##   missing value where TRUE/FALSE needed
# Solusi dengan newton_aman() pada [0, 10]
cat("Dengan newton_aman [0, 10]:\n")
## Dengan newton_aman [0, 10]:
print(newton_aman(ft, 0, 10, tol = 1e-10))
## $root
## [1] 2.262157
## 
## $iter
## [1] 5
# 3. SECANT vs NEWTON
f3_sec <- function(x) cos(x) - x
f3_nr  <- function(x) c(cos(x) - x, -sin(x) - 1)

cat("Metode Secant (x0 = 0, x1 = 1):\n")
## Metode Secant (x0 = 0, x1 = 1):
akar_sec3 <- secant(f3_sec, x0 = 0, x1 = 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
cat("\nMetode Newton-Raphson (x0 = 1):\n")
## 
## Metode Newton-Raphson (x0 = 1):
akar_nr3  <- newtonraphson(f3_nr, x0 = 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
# 4. PROYEK MINI DENGAN DATA DUMMY
# Membangkitkan 50 data dummy berdistribusi Gamma (shape = 3, rate = 0.5)
set.seed(123)
x_dummy <- rgamma(50, shape = 3, rate = 0.5)

# Menghitung statistik s = ln(rata-rata) - rata-rata(ln(x))
s <- log(mean(x_dummy)) - mean(log(x_dummy))

# Tebakan awal alpha0 = 1 / (2s) 
alpha0 <- 1 / (2 * s)

# Fungsi skor f(alpha) dan turunannya f'(alpha)
f_gamma <- function(alpha) {
  fx  <- log(alpha) - digamma(alpha) - s
  dfx <- 1 / alpha - trigamma(alpha)
  return(c(fx, dfx))
}

cat("Tebakan awal alpha0:", alpha0, "\n\n")
## Tebakan awal alpha0: 2.71212
alpha_mle <- newtonraphson(f_gamma, x0 = alpha0, tol = 1e-10)
## At iteration 1 value of x is: 2.859043 
## At iteration 2 value of x is: 2.867887 
## At iteration 3 value of x is: 2.867916 
## Algorithm converged
cat("\nTaksiran MLE alpha (Newton):", format(alpha_mle, digits = 10), "\n")
## 
## Taksiran MLE alpha (Newton): 2.867915824
# Pembanding dengan fungsi bawaan package MASS
library(MASS)
fit_mass <- fitdistr(x_dummy, "gamma")
cat("Taksiran MLE shape (MASS::fitdistr):", format(fit_mass$estimate["shape"], digits = 10), "\n")
## Taksiran MLE shape (MASS::fitdistr): 2.867921523