# Bisection Method in R
bisection_method <-
function(f, a, b, tol = 1e-6,
max_iter = 100) {
if (f(a) * f(b) >= 0) {
stop("f(a) and f(b) must
have opposite signs")
}
for (i in 1:max_iter) {
c <- (a + b) / 2
if (abs(f(c)) < tol || (b - a) / 2
< tol) {
return(c)
}
if (f(a) * f(c) < 0) {
b <- c
} else {
a <- c
}
}
stop("Bisection method did
not converge")
}
# Example 1: Solving x^3 - 4x -
9=0
f1 <- function(x) x^3 - 4*x - 9
bisection_method(f1, a = 2, b
= 3)
# Newton-Raphson Method in R
newton_raphson <- function(f, df, x0,
tol = 1e-6, max_iter = 100) {
x <- x0
for (i in 1:max_iter) {
x_new <- x - f(x) / df(x)
if (abs(x_new - x) < tol) {
return(x_new)
}
x <- x_new
}
stop("Newton-Raphson method did
not converge")
}
# Example 2: Solving cos(x) - x = 0
f2 <- function(x) cos(x) - x
df2 <- function(x) -sin(x) - 1
newton_raphson(f2, df2, x0 = 0.5)