diff options
author | Prashant S | 2019-10-04 12:27:32 +0530 |
---|---|---|
committer | GitHub | 2019-10-04 12:27:32 +0530 |
commit | ac2986488a9731cff5cbb517d8f0ef98e2561d64 (patch) | |
tree | 7bb3f64824627ef179d5f341266a664fd0b69011 /Numerical_Methods_by_E_Balaguruswamy/CH6/EX6.7 | |
parent | cbb2770fb2f88246175add29623103a56ba338b8 (diff) | |
parent | b3f3a8ecd454359a2e992161844f2fb599f8238a (diff) | |
download | R_TBC_Uploads-master.tar.gz R_TBC_Uploads-master.tar.bz2 R_TBC_Uploads-master.zip |
Added R TBC
Diffstat (limited to 'Numerical_Methods_by_E_Balaguruswamy/CH6/EX6.7')
-rw-r--r-- | Numerical_Methods_by_E_Balaguruswamy/CH6/EX6.7/Ex6_7.R | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/Numerical_Methods_by_E_Balaguruswamy/CH6/EX6.7/Ex6_7.R b/Numerical_Methods_by_E_Balaguruswamy/CH6/EX6.7/Ex6_7.R new file mode 100644 index 00000000..8212cef0 --- /dev/null +++ b/Numerical_Methods_by_E_Balaguruswamy/CH6/EX6.7/Ex6_7.R @@ -0,0 +1,54 @@ +# Example 7 Chapter 6 Page no.: 147
+# Newton-Raphson Method
+
+install.packages("numDeriv")
+library("numDeriv")
+
+# Given Function
+u <- function(x) {
+ x^2-3*x+2
+}
+
+curve(u, xlim=c(-5,5), col='blue', lwd=2, lty=2, ylab='f(x)')
+abline(h=0)
+abline(v=0)
+
+# From the curve the points in the vicinity are noted
+a <- 0
+b <-1
+
+newton.raphson <- function(f, a, b, tol = 1e-5, n = 1000) {
+ require(numDeriv) # Package for computing f'(x)
+
+ x0 <- a # Set start value to supplied lower bound
+ k <- n # Initialize for iteration results
+
+ # Check the upper and lower bounds to see if approximations result in 0
+ fa <- f(a)
+ if (fa == 0.0) {
+ return(a)
+ }
+
+ fb <- f(b)
+ if (fb == 0.0) {
+ return(b)
+ }
+
+ for (i in 1:n) {
+ dx <- genD(func = f, x = x0)$D[1] # First-order derivative f'(x0)
+ x1 <- x0 - (f(x0) / dx)
+ k[i] <- x1
+ # Checking difference between values
+ if (abs(x1 - x0) < tol) {
+ root.approx <- tail(k, n=1)
+ res <- list('root approximation' = root.approx, 'iterations' = k)
+ return(res)
+ }
+ # If Newton-Raphson has not yet reached convergence set x1 as x0 and continue
+ x0 <- x1
+ }
+ print('Too many iterations in method')
+}
+
+N <- newton.raphson(u, a, b)
+cat("The root closer to the point x=0 is",N)
\ No newline at end of file |