简体   繁体   中英

Newton root finding function does not work with sqrt(x) in R

Currently doing a homework exercise based on root finding algorithms:

A root finding algorithm can also be used to approximate certain functions. Show mathematically how the evaluation of the square root function f(x) = √x can be expressed as a root finding problem.4 Use both Newton's method and the bisection method to approximate √x for different values of x. Compare your approximations with the R function sqrt. For which values of x does the approximation work well? Does Newton's method or the bisection method perform better? How do the answers to these questions depend on your starting value?

I have the following code that worked for every function so far:

newton.function <- function(f, fPrime, nmax, eps, x0){
  n <- 1
  x1 <- x0
  result <- c()
  while((n <= nmax) && (abs(f(x1)) >= eps)){
    x1 <- (x0 - (f(x0)/fPrime(x0)))
    result <- c(result, x1)
    n <- n + 1
    x0 <- x1
  }
  iterations <- n - 1
  return(c(iterations, result[length(result)]))
}

Sqrt functions:

g <- function(x){
  x^(1/2)
}

gPrime <- function(x){
  1/(2*x^(1/2))
}

When I execute the function I either get Error in if (abs(f(x1)) <= eps) break : missing value where TRUE/FALSE needed or if the x0 = 0 I get 1 and 0 as a result.

newton.function(f = g, fPrime = gPrime, nmax = 1000, eps = 1E-8, x0 = 0)

My bisection function works equally as bad, I am stuck answering the question.

From a programming point of view, your code works as expected.

If you start with 0, which is the exact solution, you get 0, fine.

Now look what happens when starting with any other number:

x1 <- (x0 - (f(x0)/fPrime(x0))) = (x0 - (x0^(1/2)/(1/(2*x^(1/2)))))
= x0-2x0 = -x0

So if you start with a positive number, x1 will be negative after the first iteration, and the next call to f(x1) returns NaN since you ask the square root of a negative number.

The error message tells you that R can not evaluate abs(f(x1)) >= eps to TRUE or FALSE, indeed, abs(f(x1)) returns NaN and the >= operator returns also NaN in this case. This is exactly what the error message tells you.

So I advice you to look at some mathematics source to check you algorithm, but the R part is ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM