Skip to content

Commit b5d1199

Browse files
authored
Implement Newton-Raphson method in R (#196)
1 parent b90abac commit b5d1199

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
newton_raphson <- function(f, fprime, x0, tol = 1e-6, max_iter = 100) {
2+
x <- x0
3+
for (i in 1:max_iter) {
4+
deriv <- fprime(x)
5+
if (abs(deriv) < .Machine$double.eps) {
6+
warning("Derivative is zero. Newton-Raphson method fails.")
7+
return(NA)
8+
}
9+
x_new <- x - f(x) / deriv
10+
if (abs(x_new - x) < tol) {
11+
return(x_new)
12+
}
13+
x <- x_new
14+
}
15+
return(x)
16+
}

0 commit comments

Comments
 (0)