Skip to content

Instantly share code, notes, and snippets.

@jdbrice
Created July 25, 2019 15:05
Show Gist options
  • Save jdbrice/f37ed95a552acc5e0c0cb91a107e11a4 to your computer and use it in GitHub Desktop.
Save jdbrice/f37ed95a552acc5e0c0cb91a107e11a4 to your computer and use it in GitHub Desktop.
Calculate the moments of a histogram
//usr/bin/env root -l -b -q "$0( $1, \"$2\" )"; exit $?
/* Calculate the nth moment of a distribution
*
* int n : order of the moment to calculate
* TString filehist :
*/
double moment( int n = 1, TString filehist = "", float x1=0, float x2=-1 ){
cout << "Calculating moment " << n << " on " << filehist << endl;
TObjArray *tx = filehist.Tokenize(":");
if ( tx->GetEntries() < 2 ){
cout << "Usage : " << endl;
cout << "./moment.C <n> <filehist>" << endl;
cout << "\tn : order of moment to calculate" << endl;
cout << "\tfilehist : should specify the filename and the hist name separated by a \":\" e.g. \"tfile.root:hsimple\" " << endl;
exit(0);
}
TString fname = ((TObjString*)tx->At(0))->GetString();
TString hname = ((TObjString*)tx->At(1))->GetString();
TFile * f = new TFile( fname );
TH1 * h = (TH1 * )f->Get( hname );
h->Scale( 1.0 / h->Integral("width") );
// get the bounds (currently only if used as function in root prompt)
bool boundsCheck = false;
if ( x2 > x1 ) {// not defaults
boundsCheck = true;
cout << "Calculating moment in " << x1 << " to " << x2 << endl;
h->Scale( 1.0 / h->Integral( h->FindBin(x1), h->FindBin(x2), "width") );
}
float m = 0;
for ( int i = 1; i < h->GetNbinsX() + 1; i++ ){
float x = h->GetBinCenter( i );
float dx = h->GetBinWidth( i );
if ( boundsCheck && ( x-dx/2. < x1 || x+dx/2.0 > x2 ) )
continue;
float y = h->GetBinContent( i );
float _x = pow( x, n );
m += _x * dx * y;
}
return m;
}
@jdbrice
Copy link
Author

jdbrice commented Jul 25, 2019

the bounds checking may be causing a small error. Need to check how to handle normalization integral vs. bound checks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment