简体   繁体   中英

Finding the root of a function using the bisection method in R

I'm trying to find the root of the following function in R f <- x^3 + 2 * x^2 - 7 using the bisection method and the repeat function. This code results in an error:

x <- 1.3
tolerance <- 0.000001

repeat {
  f <- x^3 + 2 * x^2 - 7
  if (abs(f) < tolerance) break
  x <- (x^3 + 2 * x^2 - 7)/2
}

Error in if (abs(f) < tolerance) break : 
  missing value where TRUE/FALSE needed

I've set the initial x to be 1.3, the tolerance to be 0.000001 and I know that the root lies between 1 and 2. I have already tried to substitute the last line of the code for f instead of retyping the function, but the same error appears. Can someone help me?

Based on a very brief reading of the bisection method, I think you're adjusting x incorrectly. You should be bisecting the domain of x (the x value fed into f), not the range of f .

There are many reasons your function does not do what you want, but a primary one is that you are not even using the information you have about reasonable values for x, that is values of x that are near the root of the function. You should never be setting your x value to some value of the function for which you are trying to find a root...there's no reason these two values need to be related. For example, if the root of a function is near 100, the value of the function, f, for f(100) will be some low number. Then perhaps the value of f near 0 is some very high number. So if you start with f(x=100), you'll move x to around 0, then run f(0) and get some very big number so you'll move x to that big number, and so on. You'll be bouncing around according to f's values but not in a way that has anything to do with finding the root.

Let's try this:

x <- 1.3
tolerance <- 0.001

repeat {
  message(x)
  f <- x^3 + 2 * x^2 - 7
  if (abs(f) < tolerance) break
  x <- (x^3 + 2 * x^2 - 7)/2
  }
#1.3
#-0.7115
#-3.1738598729375
#-9.4123720943868
#-331.84120816267
#-18160827.4603406
#-2.99486226359293e+21
#-1.34307592742051e+64
#-1.21135573473788e+192
#Error in if (abs(f) < tolerance) break : 
#  missing value where TRUE/FALSE needed

As you see the x value becomes more and more negative until it's absolute value is too large for double:

x <- -1.21135573473788e+192
x^3 + 2 * x^2 - 7
#[1] NaN

You should look up the algorithm of the bisection method, because what you have implemented here is clearly not the correct algorithm.

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