jeudi 23 avril 2015

Accept std::function with arbitrary inputs as input w/o Templates

For Learning Purposes:

I am creating a small numerical methods library and I am trying to implement the gradient currently I have done 2D gradient and 3D gradient . But I want to generalize this to higher dimensions.

Currently I have :

matrix<double> analysis::gradient_2D(std::function<double(double, double)> fn, double x, double y)
{
    matrix<double> R(2, 1);

    std::function<double(double)> fnX = [fn, y](double xVar){ return fn(xVar, y); };
    std::function<double(double)> fnY = [fn, x](double yVar){ return fn(x, yVar); };

    R(1, 1) = differentiateBest(fnX, x);
    R(1, 2) = differentiateBest(fnY, y);

    return R;
}

matrix<double> analysis::gradient_3D(std::function<double(double, double, double)> fn, double x, double y, double z)
{
    matrix<double> R(3, 1);

    std::function<double(double)> fnX = [fn, y, z](double xVar){ return fn(xVar, y,z); };
    std::function<double(double)> fnY = [fn, x, z](double yVar){ return fn(x ,yVar, z); };
    std::function<double(double)> fnZ = [fn, x, y](double zVar){ return fn(x, y, zVar); };

    R(1, 1) = differentiateBest(fnX, x);
    R(1, 2) = differentiateBest(fnY, y);
    R(1, 3) = differentiateBest(fnZ, z);

    return R;
}

// Where 

double analysis::differentiateBest(std::function<double(double)> fn, double x)
{
    return derivative_1_Richardson_6O(fn,  x);
}
// For brevity , derivative_1_Richardson_6O also has the same input as differentiateBest

I know it is verbose , but I like it

Question What I would like to do is to create a

// What do I do at the ...  ? 
matrix<double> analysis::gradient_ND(std::function<double(...)> fn, matrix<double>)

So that I can pass a std::function with arbitrary input say N and I will pass a vector which has N values.

How will I go about doing this ? If the answer is too long , links will be appreciated too . Thank you.

PS: I saw a method using Templates , but if I use templates in the implementation , the I will have to change the .cpp file to something else right ? I would like to avoid. If using templates is the only way , then I will have to compromise. Thanks.

Aucun commentaire:

Enregistrer un commentaire