I am creating a class which takes as input arguments either 1
or 2
functions.
My goal is that if only one function func
is given then the member function dfunc
is calculated using num_dfunc
(which is the numerical derivative of func
and is hardcoded inside the class). If two functions are given func
and analytical_dfunc
then the derivative is calculated using the analytical version. What is the best way to achieve this?
This is a portion of my code
class MyClass
{
public:
int dim = 2;
vector<double> num_dfunc(vector<double> l0)
{
// Numerical gradient of the potential up to second order
// #TODO This should be rewritten!
vector<double> result(dim);
double eps = 0.001;
for (int i = 0; i < dim; i++)
{
vector<double> lp2 = l0;
lp2[i] += 2 * eps;
vector<double> lp1 = l0;
lp1[i] += eps;
vector<double> lm1 = l0;
lm1[i] -= eps;
vector<double> lm2 = l0;
lm2[i] -= 2 * eps;
result[i] = (-func(lp2) + 8 * func(lp1) - 8 * func(lm1) + func(lm2)) / (12 * eps);
}
return result;
}
double (*func)(vector<double>); // Potencial pointer
vector<double> (*dfunc)(vector<double>); // Gradient pointer
MyClass(double (*func)(vector<double>))
{
this->func = func;
// THIS IS WRONG
this->dfunc = num_dfunc;
}
MyClass(double (*func)(vector<double>),double (*analytical_dfunc)(vector<double>))
{
this->func = func;
// THIS IS WRONG
this->dfunc = analytical_dfunc;
}
This is a, somewhat, pythonic way of what I want to do.
PS: This is not what I have so far, I tried many things but none of them worked.
Edit : Error, on dfunc return type. Typo on analytical_dfunc