Lembaga : UIN Maulana Malik Ibrahim Malang
Jurusan : Teknik Informatika
Jawab :
Menggunakan Metode Secant
root_secant <- function(f, x, tol=1e-7, N=100){
iter <- 0
xold <- x
fxold <- f(x)
x <- xold+10*tol
while(abs(x-xold)>tol){
iter <- iter+1
if(iter>N)
stop("No solutions found")
fx <- f(x)
xnew <- x - fx*((x-xold)/(fx-fxold))
xold <- x
fxold <- fx
x <- xnew
}
root<-xnew
return(list(`function`=f, root=root, iter=iter))
}
Penyelesaian bila X = 0
f <- function(x){
x^3+2*x+2
}
root_secant(f, 0)
## $`function`
## function(x){
## x^3+2*x+2
## }
## <bytecode: 0x000000001498d118>
##
## $root
## [1] -0.770917
##
## $iter
## [1] 7
Penyelesaian bila X = 1/2 atau 0.5
f <- function(x){
x^3+2*x+2
}
root_secant(f, 0.5)
## $`function`
## function(x){
## x^3+2*x+2
## }
## <bytecode: 0x000000001327f190>
##
## $root
## [1] -0.770917
##
## $iter
## [1] 7
Menampilkan Grafik
#vektor data
x <- c(-5:1); y <- x^3+2*x+2
par(mfrow=c(1,1))
# output
plot(x, y, type="o")
Penyelesaian bila X = 0.5
f <- function(x){
sin(x)/x
}
root_secant(f, 0.5)
## $`function`
## function(x){
## sin(x)/x
## }
## <bytecode: 0x000000001390d060>
##
## $root
## [1] 6.283185
##
## $iter
## [1] 7
Penyelesaian bila X = 1
f <- function(x){
sin(x)/x
}
root_secant(f, 1)
## $`function`
## function(x){
## sin(x)/x
## }
## <bytecode: 0x0000000014fb25b8>
##
## $root
## [1] 3.141593
##
## $iter
## [1] 8
Menampilkan Grafik
#vektor data
x <- c(0.5:1); y <- sin(x)/x
par(mfrow=c(1,1))
# output
plot(x, y, type="o")
Menggunakan Metode Trapezoidal
trapezoid <- function(ftn, a, b, n = 100) {
h <- (b-a)/n
x.vec <- seq(a, b, by = h)
f.vec <- sapply(x.vec, ftn) # ftn(x.vec)
Trap <- h*(f.vec[1]/2 + sum(f.vec[2:n]) + f.vec[n+1]/2)
return(Trap)
}
Melakukan Inisialisasi fungsi
f <- function(x){
sin(x)^2
}
Menghitung Integral menggunakan Metode Trapezoidal pemisalan n = 5
trapezoid(f,0,pi,n = 6)
## [1] 1.570796
Menampilkan Grafik
#vektor data
x <- c(-5:1); y <- sin(x)^2
par(mfrow=c(1,1))
# output
plot(x, y, type="o")