Search code examples
c++nannewtons-method

Newton's method returns NaN


I wrote simple recursive version of Newton's method:

#include <cmath>

using namespace std;

double DeriveAt(double (*f)(double), double x){
    return( (f(x+0.001)-f(x-0.001))/0.002 );
};

double FindRoot(double (*f)(double), double x0){
    double corr=f(x0)/DeriveAt(f,x0);
    if(abs(corr) > 1.E-7)
            FindRoot(f, x0-corr);
    else return(x0);
};

If I call my function, e.g. FindRoot(sin, 4), NaN is returned. I checked the function by printing the value of x0 after every step, and everything seems to work unitl the last iteration. For some reason, the function calls itself once more than it actually should, probably creating something like 0/0 when calculating the last corr.


Solution

  • If I change

    if(abs(corr) > 1.E-7)
            FindRoot(f, x0-corr);
    

    to

    if(abs(corr) > 1.E-7)
            return FindRoot(f, x0-corr);
    

    then FindRoot(sin, 4) returns something approximating Pi.