0

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.

einbandi
  • 275
  • 1
  • 6
  • 3
    You're missing a `return` from your `FindRoot`. Is that the problem? – Rook Nov 15 '12 at 17:22
  • Thanks! I knew it was something stupid. With `return FindRoot(...)` it works. – einbandi Nov 15 '12 at 17:25
  • 3
    If you're in GCC land, you should make more use of things like `-Wall`, which would have given you _"test.cpp:16: warning: control reaches end of non-void function"_ – Rook Nov 15 '12 at 17:30

1 Answers1

3

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.

Rook
  • 5,125
  • 3
  • 31
  • 37