Newton

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Newton

Marcello Gambacorta COFIRI SIM
Hi QuantLibers,
I 've problems in using the Newton's method to evaluate a function.
Any idea of how to  test it in c++?
thanks in advance.
Marcello



Marcello Gambacorta
Customer Desk Cofiri SIM S.p.A.
Tel: 0039-(0)64733571
Fax:0039-(0)64884322
mail: [hidden email]
     




Reply | Threaded
Open this post in threaded view
|

Re: Newton [Mail virus free]

Luigi Ballabio-3
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;