# Get entries random

Hello, I wrote this code to calculate the emittance of particles

``````Double_t emittance=0.;
Double_t x=0;
Double_t x2=0;
Double_t xp=0;
Double_t xp2=0;
Double_t xxp=0;
Double_t sigmax2=0;
Double_t sigmaxp2=0;
Double_t sigmaxsigmaxp=0;
int jentry;
int nentries = ts->GetEntries();
double xv[10];
double xpv[10];
for(jentry=0; jentry<nentries;jentry++) {
ts->GetEntry(jentry);
x+=xv[0];
x2+=xv[0]*xv[0];
xp+=xpv[0];
xp2+=xpv[0]*xpv[0];
xxp+=xv[0]*xpv[0];
}
x*=1./nentries;
x2*=1./nentries;
xp*=1./nentries;
xp2*=1./nentries;
xxp*=1./nentries;
sigmax2=x2-x*x;
sigmaxp2=xp2-xp*xp;
sigmaxsigmaxp=xxp-x*xp;
emittance=sigmax2*sigmaxp2-sigmaxsigmaxp;
emittance=TMath::Sqrt(emittance);
emittance*=1000000;
std::cout << "N = " << nentries << "\t x = " << x << "\t x2 = " << x2 << " \t xp = " << xp <<  " \t xp2= " << xp2 << " \t xxp= " <<  xxp << std::endl;
std::cout << "sigmax2 = " << sigmax2 << "\t sigmaxp2 = " << sigmaxp2 << "\t sigmaxsigmaxp = " << sigmaxsigmaxp << " \t emittance = " << emittance  << std::endl;
results << "N = " << nentries << "\t x = " << x << "\t x2 = " << x2 << " \t xp = " << xp <<  " \t xp2= " << xp2 << " \t xxp= " <<  xxp << endl;
results << "sigmax2 = " << sigmax2 << "\t sigmaxp2 = " << sigmaxp2 << "\t sigmaxsigmaxp = " << sigmaxsigmaxp << " \t emittance = " << emittance  << endl;

``````

Now, instead of to get all the entries of the TTree and each entries just one time using
`int nentries = ts->GetEntries();`

I must get random entries and I can also get the same entry more than one time and to calculate the emittance by using these values.

I mean:

1. In my TTree ts I’ve 10^6 entries, but I want to get rando, for example, 10^4 entries allowing the possibility to get the same entry more time. Moreover, notice that I don’t want to get the first 10^4 entries…but I want to get them randomly, i.e. for exampl I get the entry number 900000 and I don’t get the entry number1000.

2. I use this code to calculate the emittance using the random 10^4 entries.

3. I repeat this operation n times…for example, I can decide to get 100 times the 10^4 random entries.

So, I would ask you how I can get a fixed number of entries randomly.

Thank you

ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided

Hi,

We don’t have such a function implemented in TTree, but you can do this by generating `10^4` random integers between 0 and `tree->GetEntries()` using `gRandom->Integer(tree->GetEntries()) for 10^4 times and then use `TTree::GetEntry(entry)` to make your calculations.

Lorenzo

Thank you @moneta

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.