Plot 2D function with callback

How can I plot a 2D function defined using C++ code?

auto fct = [](Double_t* x_ptr, Double_t* y_ptr) -> Double_t {
    return *x_ptr + *y_ptr;
};

TF2* f = new TF2("plot"), fct, 0.0, 1.0, 0.0, 1.0, 2, nullptr);
// using the constructor with a templated functor type

TCanvas* can = new TCanvas("c1", "Surf", 200, 10, 700, 700)
TPad* pad = new TPad("pad1", "surf", 0.03, 0.03, 0.98, 0.98)
pad->Draw()
f->Draw("surf");

The callback gets called multiple times with the same X coordinate, but always with Y coordinate 0. Is this a bug in ROOT, and is there any workaround?

Hi,

The second Double_t* passed in your function definition is not the y coordinate, but the function parameter arrays (used for for parametrized functions and you can set values with TF1::SetParameters ).
So if you want to implement the “x+y” function you do:

auto fct = [](Double_t* x_ptr, Double_t* ) -> Double_t {
    return x_ptr[0] + x_ptr[1];
};

TF2* f = new TF2("plot"), fct, 0.0, 1.0, 0.0, 1.0, 0);

Note also the correct syntax in the constructor. You need to specify npar=0 in this case

Best Regards

Lorenzo

seems to me this works:

{
auto fct = [](Double_t* x_ptr, Double_t* y_ptr) -> Double_t {
    return *x_ptr + *y_ptr;
};

TF2* f = new TF2("plot", fct, 0.0, 1.0, 0.0, 1.0, 2, nullptr);

f->Draw("surf");
}

Thanks