0% found this document useful (0 votes)
9 views5 pages

Bisection and Newton-Raphson in R

The document provides R implementations of two numerical methods for finding roots of functions: the Bisection Method and the Newton-Raphson Method. It includes code for both methods, along with examples demonstrating their usage to solve specific equations. The Bisection Method requires the function values at the endpoints to have opposite signs, while the Newton-Raphson Method requires the derivative of the function.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

Bisection and Newton-Raphson in R

The document provides R implementations of two numerical methods for finding roots of functions: the Bisection Method and the Newton-Raphson Method. It includes code for both methods, along with examples demonstrating their usage to solve specific equations. The Bisection Method requires the function values at the endpoints to have opposite signs, while the Newton-Raphson Method requires the derivative of the function.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# 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)

You might also like