This is an R Markdown Notebook. When you execute code within the notebook, the results appear beneath the code.
Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Ctrl+Shift+Enter.
# ===============================================================
# SOAL 1a
# Menghitung nilai eksponensial exp(x) dengan deret Maclaurin
# Rumus:
# exp(x) = 1 + x + x^2/2! + x^3/3! + ... + x^n/n!
# Fungsi menerima input x dan n (orde deret)
# ===============================================================
faktorial_manual <- function(n){
hasil <- 1
if(n == 0){
hasil <- 1
} else {
for(i in 1:n){
hasil <- hasil * i
}
}
return(hasil)
}
exp_maclaurin <- function(x, n){
total <- 0
for(i in 0:n){
suku_ke_i <- (x^i) / faktorial_manual(i)
total <- total + suku_ke_i
}
return(total)
}
hasil_exp <- exp_maclaurin(-1, 5)
print(hasil_exp)
## [1] 0.3666667
# ===============================================================
# SOAL 1b
# Menghitung nilai sin(x) dengan deret Maclaurin
# Rumus:
# sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
# Perhitungan berhenti jika suku terakhir berada di antara
# -10^-5 dan 10^-5
# ===============================================================
sin_maclaurin <- function(x){
hasil <- 0
for(i in 0:100){
suku <- ((-1)^i) * (x^(2*i + 1)) / faktorial_manual(2*i + 1)
if(suku < 10^-5 & suku > -10^-5){
break
}
hasil <- hasil + suku
}
return(hasil)
}
hasil_sin <- sin_maclaurin(pi/6)
print(hasil_sin)
## [1] 0.5000021
sin(pi/6)
## [1] 0.5
# ===============================================================
# SOAL 2
# Menghitung rata-rata bergerak M_t(k)
# Rumus:
# M_t(k) = (Y_t + Y_(t-1) + ... + Y_(t-k+1)) / k
# Pada soal digunakan k = 3
# ===============================================================
data_nilai <- c(4.1, 4.9, 6.2, 6.9, 6.8, 4.4, 5.7, 5.8, 6.9, 4.7, 6.0, 4.9)
moving_average <- function(data, k){
n <- length(data)
hasil <- c()
for(i in k:n){
jumlah <- 0
for(j in (i-k+1):i){
jumlah <- jumlah + data[j]
}
rata_rata <- jumlah / k
hasil <- c(hasil, rata_rata)
}
return(hasil)
}
hasil_mt3 <- moving_average(data_nilai, 3)
round(hasil_mt3, 2)
## [1] 5.07 6.00 6.63 6.03 5.63 5.30 6.13 5.80 5.87 5.20