samedi 2 décembre 2017

Newton-Raphson method in R, else and recursion

I am doing the newton-raphson method in a very limited way.

x0=5; epsilon = 1e-07

new_rap1 = function(ini, eps){
  f = function(a) a*a -2;
  fpr = function(a) 2*a;
  xn1 = ini-(f(ini)/fpr(ini))
  if(abs(xn1-ini) > eps){
    new_rap(xn1, eps)
  }
  xn1
}

new_rap1(x0, epsilon)

new_rap2 = function(ini, eps){
  f = function(a) a*a -2;
  fpr = function(a) 2*a;
  xn1 = ini-(f(ini)/fpr(ini))
  if(abs(xn1-ini) > eps){
    new_rap(xn1, eps)
  } else{xn1}
}

with the new_rap1 function, i got 2.7 that is incorrect answer.

But new_rap2 function gives the correct answer, that is 1.414214.

I don't know the difference between them. The only difference I see is the last else, but I do not know what makes it different.

new_rap1 = function(ini, eps){
  f = function(a) a*a -2;
  fpr = function(a) 2*a;
  xn1 = ini-(f(ini)/fpr(ini))
  if(abs(xn1-ini) > eps){
    new_rap1(xn1, eps)
  }
  xn1;print(1)
}

I tried several tests, and then I put that print statement, 1 printed 6 times. i.e.

[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1

(I guess it is the number of recursion until the answer is reached.)

Since encountered in a recursive function before encountering the print statement, should not 1 be printed only once at the end?

Thank you.

Aucun commentaire:

Enregistrer un commentaire