So I am attempting to implement an algorithm that uses Newton's method for finding the root of some given function, and I am having what I imagine is decent success except at one small but very frustrating point.
When I evaluate my function for small initial values of x_0 (i.e. less than or close to 1, [-1.1,1.1]), my function seems to work fine, but when I attempt to use it for larger values (even something like 1.2 or higher) i get this error message:
Error in while (abs(x_1 - x_0) > 10^(-1 * k) && iter < max_iter) { :
missing value where TRUE/FALSE needed
Here is my code for this problem:
g_x <- function(x){
return(x/(1+x^2)^(1/2))
}
dg_x <- function(x){
# derivative of the given function of g
return(1/(x^2+1)^(3/2))
}
newton <- function(x_0,k){
# x_0 is initial guess from which you want to being zeroing in on the root
# k is the parameter of the tolerance = 10^(-k)
if(between(g_x(x_0),-10^(-1*k)/2,10^(-1*k)/2)){
return(c(x_0,0))
}
iter <- 1
x_1 <- x_0 - (g_x(x_0)/dg_x(x_0))
while(abs(x_1-x_0) > 10^(-1*k)){
x_0 <- x_1
x_1 <- x_0 - (g_x(x_0)/dg_x(x_0))
iter <- iter + 1
}
return(c((x_1+x_0)/2, iter))
}
I have no idea what i need to do to fix this. I have been going through this line by line in the console, and the computer is capable of evaluating the expression abs(x_1-x_0) > 10^(-k) as TRUE for the first couple iterations. I am not sure why it becomes a problem at all.
It is not like the computer reches some super small/large value of x_1 that it generalizes as zero or infinity because this problem presents itself on the very first iteration of the algorithm.
In the problem we are given that: x_0 = 2 and g(x) = x/sqrt(x^2+1) so dg(x) = 1/(x^2+1)^3/2
therefore the next point to calculate is x_1 = -8
so the computer is evaluating abs(-8-2) > 10^-k. Why does this break