mardi 13 décembre 2016

Function Keeps Running

I am creating a function that finds the roots of functions. This specific algorithm attempts to sequentially reduce the width of a window where a root is known to lie. I want it to take in a function of x, the values of the window and epsilon. Epsilon is chosen by the user and the closer it is to zero the more precise the root is.
Here is my code:

`root.finder <- function(f, x_0, x_1, epsilon) {
 if (f(x_0)*f(x_1)>=0) warning("check values x_0 and x_1")
 while(abs(x_1 - x_0) >= epsilon)
 x_2 <- (x_0 + x_1)/2
 if (f(x_2)*f(x_0) < 0) {x_1 <- x_2}
 else {x_0 <- x_2}
 print(x_2)
 }`

I am trying to test it by using

root.finder(x^3-3*x+1, 0, 1, 1) 

but it runs and doesn't stop running.. What is wrong in this function?

Aucun commentaire:

Enregistrer un commentaire