Tugas 1: Newton-Raphson

# Fungsi
f <- function(x) {
  x^3 - x - 2
}

# Turunan pertama
df <- function(x) {
  3*x^2 - 1
}

# Fungsi Newton-Raphson
newton <- function(f, df, x0, tol = 1e-10,
                   max.iter = 100) {

  x <- x0
  iter <- 0

  while (abs(f(x)) > tol && iter < max.iter) {
    x <- x - f(x)/df(x)
    iter <- iter + 1
  }

  cat("Metode Newton-Raphson\n")
  cat("Akar:", x, "\n")
  cat("Jumlah iterasi:", iter, "\n\n")

  return(x)
}

# Menjalankan Newton-Raphson
hasil_newton <- newton(f, df, x0 = 1.5)
## Metode Newton-Raphson
## Akar: 1.52138 
## Jumlah iterasi: 3
# TUGAS 1: BISECTION

bisection <- function(f, a, b, tol = 1e-10,
                      max.iter = 100) {

  iter <- 0

  while (iter < max.iter) {

    c <- (a + b)/2
    iter <- iter + 1

    if (abs(f(c)) <= tol) {
      break
    }

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

  cat("Metode Bisection\n")
  cat("Akar:", c, "\n")
  cat("Jumlah iterasi:", iter, "\n\n")

  return(c)
}

# Menjalankan Bisection
hasil_bisection <- bisection(f, a = 1, b = 2)
## Metode Bisection
## Akar: 1.52138 
## Jumlah iterasi: 33
# TUGAS 1: UN IROOT

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

cat("Metode uniroot()\n")
## Metode uniroot()
cat("Akar:", hasil_uniroot$root, "\n")
## Akar: 1.52138
cat("Jumlah iterasi:", hasil_uniroot$iter, "\n\n")
## Jumlah iterasi: 8
# PERBANDINGAN HASIL

perbandingan <- data.frame(
  Metode = c("Newton-Raphson", "Bisection", "uniroot"),
  Akar = c(
    hasil_newton,
    hasil_bisection,
    hasil_uniroot$root
  ),
  Iterasi = c(
    NA,
    NA,
    hasil_uniroot$iter
  )
)

print(perbandingan)
##           Metode    Akar Iterasi
## 1 Newton-Raphson 1.52138      NA
## 2      Bisection 1.52138      NA
## 3        uniroot 1.52138       8

interpretasi : Hasil perhitungan menunjukkan bahwa Newton-Raphson memperoleh akar 1,521379707 dengan 3 iterasi, sedangkan Bisection membutuhkan 33 iterasi. Kedua metode menghasilkan akar yang hampir sama, tetapi Newton-Raphson lebih cepat mencapai hasil. Fungsi uniroot() digunakan sebagai pembanding untuk memastikan kesesuaian hasil akar.

#Tugas 2 : Kuantil t

# Fungsi dan turunan
f_t <- function(x) {
  pt(x, df = 9) - 0.975
}

df_t <- function(x) {
  dt(x, df = 9)
}

# Metode Newton-Raphson
newton_t <- function(x0, tol = 1e-10, maxiter = 100) {

  x <- x0
  iter <- 0
  status <- "Konvergen"

  repeat {

    # Menghitung nilai fungsi
    nilai_f <- f_t(x)

    # Memeriksa konvergensi
    if (!is.finite(nilai_f)) {
      status <- "Gagal: nilai fungsi tidak valid"
      break
    }

    if (abs(nilai_f) < tol) {
      break
    }

    # Menghitung turunan
    turunan <- df_t(x)

    # Memeriksa nilai turunan
    if (!is.finite(turunan) || abs(turunan) < 1e-14) {
      status <- "Gagal: turunan terlalu kecil"
      break
    }

    # Iterasi Newton-Raphson
    xbaru <- x - f_t(x)/turunan

    # Memeriksa hasil iterasi
    if (!is.finite(xbaru)) {
      status <- "Gagal: nilai iterasi tidak valid"
      break
    }

    iter <- iter + 1

    # Memeriksa konvergensi
    if (abs(xbaru - x) < tol &&
        abs(f_t(xbaru)) < tol) {
      x <- xbaru
      break
    }

    x <- xbaru

    # Batas maksimum iterasi
    if (iter >= maxiter) {
      status <- "Gagal: iterasi maksimum tercapai"
      break
    }
  }

  list(
    hasil = x,
    iterasi = iter,
    nilai_f = f_t(x),
    status = status
  )
}


# Newton-Raphson dengan x0 = 1
hasil_x1 <- newton_t(1)

cat("Hasil Newton-Raphson x0 = 1:\n")
## Hasil Newton-Raphson x0 = 1:
print(hasil_x1)
## $hasil
## [1] 2.262157
## 
## $iterasi
## [1] 6
## 
## $nilai_f
## [1] -1.010303e-14
## 
## $status
## [1] "Konvergen"
# Newton-Raphson dengan x0 = 10
hasil_x10 <- newton_t(10)

cat("\nHasil Newton-Raphson x0 = 10:\n")
## 
## Hasil Newton-Raphson x0 = 10:
print(hasil_x10)
## $hasil
## [1] -16776.42
## 
## $iterasi
## [1] 1
## 
## $nilai_f
## [1] -0.975
## 
## $status
## [1] "Gagal: turunan terlalu kecil"
# Menghitung menggunakan fungsi qt()
hasil_qt <- qt(0.975, df = 9)

cat("\nHasil menggunakan qt():\n")
## 
## Hasil menggunakan qt():
print(hasil_qt)
## [1] 2.262157
# Membandingkan hasil
perbandingan <- data.frame(
  Metode = c(
    "Newton-Raphson (x0=1)",
    "Newton-Raphson (x0=10)",
    "Fungsi qt()"
  ),

  Hasil = c(
    hasil_x1$hasil,
    hasil_x10$hasil,
    hasil_qt
  ),

  Iterasi = c(
    hasil_x1$iterasi,
    hasil_x10$iterasi,
    NA
  ),

  Status = c(
    hasil_x1$status,
    hasil_x10$status,
    "Berhasil"
  )
)

print(perbandingan)
##                   Metode         Hasil Iterasi                       Status
## 1  Newton-Raphson (x0=1)      2.262157       6                    Konvergen
## 2 Newton-Raphson (x0=10) -16776.419496       1 Gagal: turunan terlalu kecil
## 3            Fungsi qt()      2.262157      NA                     Berhasil

interpretasi : Metode Newton-Raphson dengan tebakan awal (x0=1) berhasil memperoleh hasil yang sesuai dengan fungsi qt(), yaitu 2,262157. Sementara itu, penggunaan (x0=10) menyebabkan algoritma gagal konvergen karena nilai turunannya terlalu kecil. Hal ini menunjukkan bahwa pemilihan nilai awal berpengaruh terhadap keberhasilan metode Newton-Raphson.

#Tugas 3 : Secant

# Fungsi
f <- function(x) {
  cos(x) - x
}

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


# Metode Secant
secant <- function(x0, x1, tol = 1e-10,
                   maxiter = 100) {

  iter <- 0
  evaluasi <- 2

  f0 <- f(x0)
  f1 <- f(x1)

  repeat {

    if (!is.finite(f0) || !is.finite(f1) ||
        abs(f1 - f0) < 1e-15) {
      status <- "Gagal konvergen"
      break
    }

    x2 <- x1 - f1 * (x1 - x0)/(f1 - f0)
    iter <- iter + 1

    f2 <- f(x2)
    evaluasi <- evaluasi + 1

    if (!is.finite(x2) || !is.finite(f2)) {
      status <- "Gagal konvergen"
      break
    }

    if (abs(x2 - x1) < tol && abs(f2) < tol) {
      status <- "Konvergen"
      break
    }

    if (iter >= maxiter) {
      status <- "Gagal konvergen"
      break
    }

    x0 <- x1
    x1 <- x2
    f0 <- f1
    f1 <- f2
  }

  list(
    akar = x2,
    iterasi = iter,
    evaluasi = evaluasi,
    status = status
  )
}


# Metode Newton-Raphson
newton_cos <- function(x0, tol = 1e-10,
                       maxiter = 100) {

  iter <- 0
  evaluasi_f <- 1
  evaluasi_df <- 0
  x <- x0

  repeat {

    fx <- f(x)
    dfx <- df(x)

    evaluasi_f <- evaluasi_f + 1
    evaluasi_df <- evaluasi_df + 1

    if (!is.finite(fx) || !is.finite(dfx) ||
        abs(dfx) < 1e-15) {
      status <- "Gagal konvergen"
      break
    }

    xbaru <- x - fx/dfx
    iter <- iter + 1

    if (!is.finite(xbaru)) {
      status <- "Gagal konvergen"
      break
    }

    if (abs(xbaru - x) < tol &&
        abs(f(xbaru)) < tol) {
      evaluasi_f <- evaluasi_f + 1
      x <- xbaru
      status <- "Konvergen"
      break
    }

    if (iter >= maxiter) {
      status <- "Gagal konvergen"
      break
    }

    x <- xbaru
  }

  list(
    akar = x,
    iterasi = iter,
    evaluasi_fungsi = evaluasi_f,
    evaluasi_turunan = evaluasi_df,
    status = status
  )
}


# Menjalankan kedua metode
hasil_secant <- secant(0, 1)
hasil_newton_cos <- newton_cos(1)

# Menampilkan hasil
cat("Hasil Metode Secant:\n")
## Hasil Metode Secant:
print(hasil_secant)
## $akar
## [1] 0.7390851
## 
## $iterasi
## [1] 6
## 
## $evaluasi
## [1] 8
## 
## $status
## [1] "Konvergen"
cat("\nHasil Metode Newton-Raphson:\n")
## 
## Hasil Metode Newton-Raphson:
print(hasil_newton_cos)
## $akar
## [1] 0.7390851
## 
## $iterasi
## [1] 5
## 
## $evaluasi_fungsi
## [1] 7
## 
## $evaluasi_turunan
## [1] 5
## 
## $status
## [1] "Konvergen"
# Tabel perbandingan
perbandingan <- data.frame(
  Metode = c("Secant", "Newton-Raphson"),

  Akar = c(
    hasil_secant$akar,
    hasil_newton_cos$akar
  ),

  Iterasi = c(
    hasil_secant$iterasi,
    hasil_newton_cos$iterasi
  ),

  Evaluasi_Fungsi = c(
    hasil_secant$evaluasi,
    hasil_newton_cos$evaluasi_fungsi
  ),

  Evaluasi_Turunan = c(
    NA,
    hasil_newton_cos$evaluasi_turunan
  ),

  Status = c(
    hasil_secant$status,
    hasil_newton_cos$status
  )
)

print(perbandingan)
##           Metode      Akar Iterasi Evaluasi_Fungsi Evaluasi_Turunan    Status
## 1         Secant 0.7390851       6               8               NA Konvergen
## 2 Newton-Raphson 0.7390851       5               7                5 Konvergen

interpretasi : Metode Secant memperoleh akar sekitar 0,7390851332 dengan 6 iterasi, sedangkan Newton-Raphson memperoleh akar yang sama dengan 5 iterasi. Newton-Raphson membutuhkan iterasi lebih sedikit, tetapi Secant tidak memerlukan perhitungan turunan sehingga lebih sederhana dalam penggunaannya.

#Tugas 4 : Proyek mini

# Memanggil package
library(MASS)
## Warning: package 'MASS' was built under R version 4.5.3
# Data pengamatan
x <- c(2, 3, 4, 5, 6, 7, 8, 9, 10, 12)

# Menghitung konstanta
n <- length(x)
xbar <- mean(x)

s <- log(xbar) - mean(log(x))

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


# Fungsi MLE
f <- function(alpha) {
  log(alpha) - digamma(alpha) - s
}

# Turunan fungsi
df <- function(alpha) {
  1/alpha - trigamma(alpha)
}


# Metode Newton-Raphson
newton_gamma <- function(alpha0, tol = 1e-10,
                         maxiter = 100) {

  alpha <- alpha0
  iter <- 0
  status <- "Konvergen"

  repeat {

    # Memeriksa nilai fungsi dan turunan
    if (!is.finite(f(alpha)) ||
        !is.finite(df(alpha)) ||
        abs(df(alpha)) < 1e-14) {
      status <- "Gagal: turunan tidak valid"
      break
    }

    # Iterasi Newton-Raphson
    alpha_baru <- alpha - f(alpha)/df(alpha)

    # Memeriksa nilai alpha
    if (!is.finite(alpha_baru) || alpha_baru <= 0) {
      status <- "Gagal: nilai alpha tidak valid"
      break
    }

    iter <- iter + 1

    # Memeriksa konvergensi
    if (abs(alpha_baru - alpha) < tol &&
        abs(f(alpha_baru)) < tol) {
      alpha <- alpha_baru
      break
    }

    alpha <- alpha_baru

    # Batas maksimum iterasi
    if (iter >= maxiter) {
      status <- "Gagal: iterasi maksimum tercapai"
      break
    }
  }

  list(
    alpha = alpha,
    iterasi = iter,
    nilai_f = f(alpha),
    status = status
  )
}


# Menjalankan estimasi Newton-Raphson
hasil_gamma <- newton_gamma(alpha0)

cat("Hasil Newton-Raphson:\n")
## Hasil Newton-Raphson:
print(hasil_gamma)
## $alpha
## [1] 4.061241
## 
## $iterasi
## [1] 4
## 
## $nilai_f
## [1] 4.440892e-16
## 
## $status
## [1] "Konvergen"
# Estimasi menggunakan MASS::fitdistr
hasil_fit <- MASS::fitdistr(
  x,
  densfun = "gamma"
)

cat("\nHasil MASS::fitdistr:\n")
## 
## Hasil MASS::fitdistr:
print(hasil_fit)
##      shape       rate   
##   4.0612575   0.6153421 
##  (1.7467640) (0.2817241)
# Perbandingan hasil
perbandingan <- data.frame(
  Metode = c("Newton-Raphson", "MASS::fitdistr"),

  Alpha = c(
    hasil_gamma$alpha,
    hasil_fit$estimate["shape"]
  ),

  Iterasi = c(
    hasil_gamma$iterasi,
    NA
  ),

  Status = c(
    hasil_gamma$status,
    "Berhasil"
  )
)

cat("\nTabel Perbandingan:\n")
## 
## Tabel Perbandingan:
print(perbandingan)
##               Metode    Alpha Iterasi    Status
##       Newton-Raphson 4.061241       4 Konvergen
## shape MASS::fitdistr 4.061258      NA  Berhasil

interpretasi : Hasil perhitungan menunjukkan bahwa metode Newton-Raphson memperoleh estimasi parameter bentuk Gamma sebesar 4,061241. Nilai tersebut mendekati hasil dari fungsi MASS::fitdistr. Hal ini menunjukkan bahwa kedua metode memberikan hasil estimasi yang konsisten dalam menentukan parameter bentuk distribusi Gamma.