Use TTreeFormula right afer tree->Fill()

I am wondering whether or not treeformula->EvalInstance() must be called after having filled the entire tree? I define a pointer of treeformula after creating new Tree, I would use EvalInstance() in the loop of filling the tree. If I didn’t re-define a pointer of treeformula before calling EvalInstance(), evalinstance will return 0. I am confused about that since when I define the first treeformula, I have set tree pointer to the treeformula, why must I re-define?

Please see my example code attached.

test_TTreeFormulaAfterFill.C (1.18 KB)

You must define the TTreeFormula after the creation of the tree branches, otherwise the Tree variables are unknown to the formula.
You do not have to call GetEntry (the Tree knows the addresses of your variables).
see code below

[code]void test_TTreeFormulaAfterFill() {

TTree * t_new = new TTree(“t_new”, “Create new tree”);

float var1;
float var2;
t_new->Branch(“var1”, &var1, “var1/F”);
t_new->Branch(“var2”, &var2, “var2/F”);
TTreeFormula * tf_new = new TTreeFormula(“tf_new”, “var1/var2”, t_new);

TRandom * rand = new TRandom;
for (int ievt=0; ievt<10; ievt++) {

var1 = rand->Rndm();
var2 = rand->Gaus();

printf("Before filling: ");
printf("  var1: %f  var2: %f \n", var1, var2);

printf("var1/var2 from formular: %10.3f <=>%10.3f\n\n", (float)tf_new->EvalInstance(), (float)var1/var2);




Oh, I see. Removed my puzzle. Thanks!

I have another question about this thread.

If I do in the way:

printf("var1/var2 from formular: %10.3f <=>%10.3f\n\n", (float)tf_new->EvalInstance(), (float)var1/var2); 
   t_new->Fill(); // 

(call EvalInstance before filling) then tf_new->EvalInstance() will give a value of last event, right?


[quote]will give a value of last event, right? [/quote]Most likely not.
It will give the element that is stored at the entry number returned by t_new->GetReadEntry().

Before calling EvalInstance, you should always make a call to LoadEntry (t->LoadEntry(what_I_want); ) to tell the TTreeFormula object which entry you want to read.

If you intent is to get the last value you should do:t->LoadTree(t->GetEntries()-1);


Thanks. I guess you really mean t->LoadTree(ientry) instead of t->LoadEntry(ientry).