[R] Newton-RaphsonMethod

Daniel Nordlund djnord|und @end|ng |rom gm@||@com
Sun Feb 24 20:14:16 CET 2019


On 2/24/2019 5:25 AM, malika yassa via R-help wrote:
> HELLOplease I want to approximate the solution of the equation f(x)=x*(x-2)+log(x)=0
> for that i did this program
>
> f <- function(x){x*(x-2)+log(x)}
> x <- c(1 : 2)
> f(x)
> h <- 1e-7
> df.dx <- function(x){(f(x + h) - f(x)) / h}
> df.dx(3/2);df.dx(2)
>   newton <- function(f, tol = 1e-7, x0 = 3/2, N = 100){
>   h = 1e-7
>   i = 1; x1 = x0
>   p = numeric(N)
>   while (i <= N) {
>   df.dx = (f(x + h) - f(x)) / h
>   x1 = (x0 - (f(x0) / df.dx))
>   p[1] = x1
>   i = i + 1
>   if (abs(x1 - x0) < tol) break
>   x0 = x1
>   }
>   return(p[1 : (i-1)])
>   }
>   app <- newton(f, x0 = 3/2)
>
> but i cann't find this approximation
> please can you help me?
>
>
>
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

As Bert pointed out there is a no homework policy on this list. But I 
will point out that when I ran your presented code, I got a lot of 
warnings.  They were not immediately informative (at least to me) 
because of a subtle programming error in your code.  Your main problem 
(but not your only one) is in the calculation of the derivative of the 
function inside the while loop. The following line is the problem:

df.dx = (f(x + h) - f(x)) / h

I will leave the solution of the problem to you.

Dan

-- 
Daniel Nordlund
Port Townsend, WA  USA



More information about the R-help mailing list