# ==============================================================================
# Name  : Maulana Ainu Rohmah
# NRP   : 5003251077
# Class : D
# Date  : 13/04/2026
# ==============================================================================

# Exercise A
# ------------------------------------------------------------------------------
# Normal Distribution / Distribusi Normal
# ------------------------------------------------------------------------------
dnormal <- function(x){
  (1/sqrt(2*pi)) * exp(-x^2/2)
}

simpson <- function(a, b, n, f){
  if( n %% 2 != 0){
    stop("n harus genap")
  }
  
  h <- (b-a) / n
  x <- a
  
  hasil <- f(a) + f(b)
  
  for(i in 1:n-1){
    x <- x+h
    if(i %% 2 == 1){
      hasil <- hasil + 4*f(x)
    } else {
      hasil <- hasil + 2*f(x)
    }
  }
  hasil <- hasil * h/3
  return(hasil)
}
simpson(0, 1, 10, dnormal)
## [1] 0.3518401
integrate(dnormal, 0, 1)
## 0.3413447 with absolute error < 3.8e-15
pnorm(1) - pnorm(0)
## [1] 0.3413447
# Exercise B
# ------------------------------------------------------------------------------
# Exponential Distribution
# ------------------------------------------------------------------------------
dexponential <- function(x){
  exp(-x)
}
trapezoidal <- function(a, b, n, f){
  h = (b-a) / n
  x <- a
  luas <- f(a) + f(b)
  
  for(i in 1:(n-1)){
    x <- x + h
    luas <- luas + 2*f(x)
  }
  luas <- luas * h / 2
  return(luas)
}
trapezoidal(0, 1, 10, dexponential)
## [1] 0.6326472
integrate(dexponential, 0, 1)
## 0.6321206 with absolute error < 7e-15
dexponential <- function(x){
  exp(-x)
}
simpson <- function(a, b, n, f){
  if( n %% 2 != 0){
    stop("n harus genap")
  }
  
  h <- (b-a) / n
  x <- a
  
  hasil <- f(a) + f(b)
  
  for(i in 1:n-1){
    x <- x+h
    if(i %% 2 == 1){
      hasil <- hasil + 4*f(x)
    } else {
      hasil <- hasil + 2*f(x)
    }
  }
  hasil <- hasil * h/3
  return(hasil)
}
simpson(0, 1, 10, dexponential)
## [1] 0.6366282
integrate(dexponential, 0, 1)
## 0.6321206 with absolute error < 7e-15