A place to put your answers to assignment 2a. That assignment is as follows:
Push it to your version of this repository as a knitted .Rmd or .md of .pdf file This assignment is due at midnight on Friday Feb 25th.
## Secant Method Function 2
## Purpose: Finding roots of nonlinear equations
set.seed(2020)
cos.func <- function(x) { cos(x)-(x) } curve(expr = cos.func, col=‘green’, lwd=2, lty=2, xlim=c(0,3)) abline(h=0) abline(v=0)
## Root of function within interval (x=1.5)
x0 <- 1 x1 <- 2 a <- cos(x0)-x0 b <- cos(x1)-x1
## Draw Secant Line using determined points
curve(expr = cos.func, col=‘green’, lwd=2, lty=2, xlim=c(0,3)) abline(h=0) abline(v=0) points(x0, a, cex=1.25, pch=21, bg=‘green’, col=‘green’) points(x1, b, cex=1.25, pch=21, bg=‘green’, col=‘green’) segments(x0, a, b, col=‘red’, lwd = 2)
## New Secant Line
x1 <- 1 x2 <- 2 a <- cos(x1)-x1 b <- cos(x2)-x2
curve(expr = cos.func, col=‘blue’, lwd=2, lty=2, xlim=c(0,3)) abline(h=0) abline(v=0) points(x1, a, cex=1.25, pch=21, bg=‘blue’, col=‘blue’) points(x2, b, cex=1.25, pch=21, bg=‘blue’, col=‘blue’) segments(x1, a, x2, b, col=‘red’, lwd = 2)
SMfzero(cos.func, 1, 2) secant.method(cos.func, 1, 2)
## Test Using Newton-Raphson Method
secant.method <- function(f, x0, x1, to1 = 1e-9, n = 500) { for (i in 1:n) { x2 <- x1 - f(x1) / ((f(x1) - f(x0)) / (x1 - x0)) if (abs(x2-x1) < to1) { return(x2) } x0 <- x1 x1 <- x2 } } secant.method(cos.func, 1, 2)
## Secant Method Function 2
func2 <- function(x) { log(x)-exp(-x) }
x0 <- 1 x1 <- 2 a <- log(x0)-exp(-x0) b <- log(x1)-exp(-x1)
## Draw Secant Line using determined points
curve(expr = func2, col=‘green’, lwd=2, lty=2, xlim=c(0,3)) abline(h=0) abline(v=0) points(x0, a, cex=1.25, pch=21, bg=‘green’, col=‘green’) points(x1, b, cex=1.25, pch=21, bg=‘green’, col=‘green’) segments(x0, a, b, col=‘red’, lwd = 2)
## New Secant Line
x1 <- 1 x2 <- 2 a <- log(x1)-exp(-x1) b <- log(x2)-exp(-x2)
curve(expr = func2, col=‘blue’, lwd=2, lty=2, xlim=c(0,3)) abline(h=0) abline(v=0) points(x1, a, cex=1.25, pch=21, bg=‘blue’, col=‘blue’) points(x2, b, cex=1.25, pch=21, bg=‘blue’, col=‘blue’) segments(x1, a, x2, b, col=‘red’, lwd = 2)
SMfzero(func2, 1, 3) secant.method(func2, 1, 3)