Separately adding branches to TTrees

Hello,

I’m trying to separately add a branch to a TTree but I’m not being very successfull. Here’s a simplified version of what I want to accomplish:

void testing_branch(){


    TFile hfile("htree_testing.root","RECREATE","testing this");


    // Create a ROOT Tree
    TTree *tree = new TTree("tree","A tree");

	int nevents = 10;

	double distance, event_x, event_y, multiplication;

    tree->Branch("distance", &distance,"distance of the event/D");
    tree->Branch("event_x", &event_x,"x position of the event/D");
    tree->Branch("event_y", &event_y,"y position of the event/D");

    TBranch *bmultiplication = tree->Branch("multiplication", &multiplication,"multiplication/D");

  	TRandom3 *random_number_generator = new TRandom3();


	for (int i = 0; i < nevents; ++i)
	{

		event_x = random_number_generator->Uniform(0, 50);
		event_y = random_number_generator->Uniform(0, 50);
		distance = TMath::Sqrt(TMath::Power(event_x,2) + TMath::Power(event_y,2));
		tree->Fill();
	}


	for (int i = 0; i < nevents; ++i)
	{

		tree->GetEntry(i);
		multiplication = 5;
		bmultiplication->Fill();
	}


	tree->Scan();
	tree->Print();

	hfile.Write();
    hfile.Close();

	std::cout << ">>>>>>>> Reached the end <<<<<<<<<<" << std::endl;


}

For some reason, the “multiplication” branch has 20 entries and not 10, as I would expect… I want to add branches that are calculated in different for-loops… How do I go about doing that?

Thank you in advance,

#include "TFile.h"
#include "TTree.h"
#include "TBranch.h"
#include "TRandom.h"
#include "TMath.h"

#include <iostream>

void testing_branch() {
  TFile *hfile = TFile::Open("htree_testing.root", "RECREATE", "testing this", 6);
  TTree *tree = new TTree("tree", "A tree");
  
  double distance, event_x, event_y, multiplication;
  
  tree->Branch("distance", &distance, "distance/D");
  tree->Branch("event_x", &event_x, "x_position/D");
  tree->Branch("event_y", &event_y, "y_position/D");
  
  int nevents = 10;
  
  for (int i = 0; i < nevents; i++) {
    event_x = gRandom->Uniform(0, 50);
    event_y = gRandom->Uniform(0, 50);
    distance = TMath::Sqrt(TMath::Power(event_x, 2) + TMath::Power(event_y, 2));
    tree->Fill();
  }
  
  TBranch *bmultiplication = tree->Branch("multiplication", &multiplication, "multiplication/D");
  
  for (int i = 0; i < nevents; i++) {
    tree->GetEntry(i);
    multiplication = 5;
    bmultiplication->Fill();
  }
  
  tree->Scan();
  tree->Print();
  
  tree->Write();
  delete hfile; // automatically deletes tree, too
  
  std::cout << ">>>>>>>> Reached the end <<<<<<<<<<" << std::endl;
}

That does work, thank you!

For posterity sake, the problem was that I was creating the multiplication branch and filling it with nothing. I should’ve only created it when I needed it.

Thank you.