MPD78
06-29-2012, 12:48 PM
Hi all,
Can someone please provide an example of how to create a functor that can have two variables being passed into it?
For example:
I need to create a functor that has two variables, Val1 and Val2.
The resulting equation is Val1+Val2*x
That equation needs to be used by qtrap.
The end result is the integral of the simple linear function.
Thanks
Matt
davekw7x
06-30-2012, 01:06 PM
...functor that can have two variables being passed into it?...
Matt
// Driver for routine qtrap
//
// davekw7x
// Use whatever path you need...
#include "../code/nr3.h"
#include "../code/quadrature.h"
// Test function to integrate is a functor.
//
struct Ftor
{
// Parameters will be set by constructor
Doub a, b;
// Constructor
Ftor(Doub aa, Doub bb): a(aa), b(bb){}
// Overloaded () operator that will be used by qtrap.
// Must have this footprint: a function that
// returns a double, and has a single parameter that
// is a const double.
// (Could use standard C++ "double" for data types.)
//
Doub operator ()(const Doub x) const
{
return a*x + b;
}
};
int main()
{
// Set up limits of integration to feed to qtrap
Doub xmin = -1.0, xmax = 1.0;
// Set up parameters for the functor so that qtrap
// can integrate.
//
Doub a = 2.0, b = 7.0;
Ftor f(a, b);
Doub value = qtrap(f, xmin, xmax);
cout << "From qtrap, for a = " << a << " and b = " << b << ":" << endl
<< "The integral of a*x+b as x goes from "
<< xmin << " to " << xmax
<< " is " << scientific << value << endl;
return 0;
}
Output:
From qtrap, for a = 2 and b = 7:
The integral of a*x+b as x goes from -1 to 1 is 1.400000e+01
Regards,
Dave
MPD78
06-30-2012, 07:47 PM
Dave,
Thanks.
I figured it out, not long after I posted this question. I had simple error in the way I laid the struct out. I just hadn't had a chance to log in to the forum until now.
Thanks
Matt