CMS 3D CMS Logo

SimpleHistogramGenerator.cc
Go to the documentation of this file.
3 
4 #include <cmath>
5 #include "TH1.h"
6 // #include <iostream>
7 
9  //myHisto(histo),
10  //theXaxis(histo->GetXaxis()),
11  nBins(histo->GetXaxis()->GetNbins()),
12  xMin(histo->GetXaxis()->GetXmin()),
13  xMax(histo->GetXaxis()->GetXmax()),
14  binWidth((xMax-xMin)/(float)nBins)
15 {
16  integral.reserve(nBins+2);
17  integral.push_back(0.);
18  for ( int i=1; i<=nBins; ++i )
19  integral.push_back(integral[i-1]+histo->GetBinContent(i));
20  integral.push_back(integral[nBins]);
21  nEntries = integral[nBins+1];
22  for ( int i=1; i<=nBins; ++i )
23  integral[i] /= nEntries;
24 
25 }
26 
27 
28 double
30 
31  // return a random number distributed according the histogram bin contents.
32  // NB Only valid for 1-d histograms, with fixed bin width.
33 
34  double r1 = random->flatShoot();
35  int ibin = binarySearch(nBins,integral,r1);
36  double x = xMin + (double)(ibin) * binWidth;
37  if (r1 > integral[ibin]) x +=
38  binWidth*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
39  return x;
40 
41 }
42 
43 int
45  const std::vector<float>& array,
46  const double& value) const
47 {
48  // Binary search in an array of n values to locate value.
49  //
50  // Array is supposed to be sorted prior to this call.
51  // If match is found, function returns position of element.
52  // If no match found, function gives nearest element smaller than value.
53 
54  int nabove, nbelow, middle;
55  nabove = n+1;
56  nbelow = 0;
57  while(nabove-nbelow > 1) {
58  middle = (nabove+nbelow)/2;
59  if (value == array[middle-1]) return middle-1;
60  if (value < array[middle-1]) nabove = middle;
61  else nbelow = middle;
62  }
63  return nbelow-1;
64 }
double nEntries
Number of entries.
double flatShoot(double xmin=0.0, double xmax=1.0) const
std::vector< float > integral
Integral.
TRandom random
Definition: MVATrainer.cc:138
Definition: value.py:1
double generate(RandomEngineAndDistribution const *) const
The random generation.
int nBins
Pointer to the histogram.
int binarySearch(const int &n, const std::vector< float > &array, const double &value) const