trapesium <- function(f,a,b,n) {
h <- (b - a)/n
jumlah <- 0
for (i in 1:(n-1)) {
jumlah <- jumlah + f(a+i*h) #f(x1)+....+f(x(n-1))
}
I<- h/2* (f(a) +2*jumlah + f(b))
return(I)
}
f <- function(t) {2 * t^2 +1}
trapesium(f,0,6,6)
## [1] 152
#simpson
simpson <-function(f,a,b,n) {
h <- (b-a) / n
ganjil <- 0
genap <- 0
for (i in 1: (n-1)) {
if (i %% 2 == 1){
ganjil <- ganjil + f(a + i * h) #
} else {
genap <- genap + f(a + i * h)
}
}
I <- h / 3 * (f(a) + 4 * ganjil + 2 * genap + f(b))
return (I)
}
C <- function(t) { 10 * t * exp(-0.5*t) }
simpson(C, 0,4, 8)
## [1] 23.75731
turunan_maju <- function(f, x, h) {
(f(x + h) - f(x)) / h
}
turunan_mundur <- function(f, x, h) {
(f(x) - f(x - h)) / h
}
turunan_tengah <- function(f, x, h) {
(f(x + h) - f(x - h)) / (2 * h)
}
turunan_kedua <- function(f, x, h) {
(f(x + h) - 2 * f(x) + f(x - h)) / h^2
}
C <- function(t) { t^3 + 2 * t^2 }
turunan_maju(C, 2, 0.1)
## [1] 20.81
turunan_mundur(C, 2, 0.1)
## [1] 19.21
turunan_tengah(C, 2, 0.1)
## [1] 20.01
turunan_kedua(C, 2, 0.1)
## [1] 16
# Pembanding: turunan simbolik
d1 <- D(expression(t^3 + 2 * t^2), "t")
d1
## 3 * t^2 + 2 * (2 * t)
eval(d1, list(t = 2))
## [1] 20
d2 <- D(d1, "t")
d2
## 3 * (2 * t) + 2 * 2
eval(d2, list(t = 2))
## [1] 16