Login  Register

Re: Newton [Mail virus free]

Posted by Luigi Ballabio-3 on Jul 10, 2001; 4:07pm
URL: http://quantlib.414.s1.nabble.com/Newton-tp1745p1746.html

At 12:59 PM 7/10/01 +0200, Marcello Gambacorta COFIRI SIM wrote:
>Hi QuantLibers,
>I 've problems in using the Newton's method to evaluate a function.
>Any idea of how to  test it in c++?

Ciao Marcello,
         here's a simple example. You'll have to wrap it in some kind of
main() to make it compile and run. Also I didn't test it myself, I just
wrote it.
Feel free to expand it into a meaningful example and contribute it :)

Bye,
         Luigi

-----------------------------------------

// derive your function from ObjectiveFunction and implement ()
// and derivative() - Newton requires the latter as well
class MyFunction : public QuantLib::ObjectiveFunction {
   public:
     double operator()(double x) const {
          return x*x-1.0;    // x^2-1 - lame, I know.
     }
     double derivative(double x) const {
         return 2.0*x;
     }
};

// create an instance
MyFunction f;
f(0.0);              // returns -1.0
f(2.0);              // returns 3.0
f.derivative(1.0);   // returns 2.0

// instantiate the solver
Newton solver;

// use it to find the root of f between 0.0 and 3.0
// hopefully it will return 1.0 within the given accuracy
double accuracy = 0.00001;
double guess = 1.5;
double root = solver.solve(f,accuracy,guess,0.0,3.0);

std::cout << "The root is " << root << std::endl;