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  integral.reserve(nBins + 2);
16  integral.push_back(0.);
17  for (int i = 1; i <= nBins; ++i)
18  integral.push_back(integral[i - 1] + histo->GetBinContent(i));
19  integral.push_back(integral[nBins]);
20  nEntries = integral[nBins + 1];
21  for (int i = 1; i <= nBins; ++i)
22  integral[i] /= nEntries;
23 }
24 
26  // return a random number distributed according the histogram bin contents.
27  // NB Only valid for 1-d histograms, with fixed bin width.
28 
29  double r1 = random->flatShoot();
30  int ibin = binarySearch(nBins, integral, r1);
31  double x = xMin + (double)(ibin)*binWidth;
32  if (r1 > integral[ibin])
33  x += binWidth * (r1 - integral[ibin]) / (integral[ibin + 1] - integral[ibin]);
34  return x;
35 }
36 
37 int SimpleHistogramGenerator::binarySearch(const int& n, const std::vector<float>& array, const double& value) const {
38  // Binary search in an array of n values to locate value.
39  //
40  // Array is supposed to be sorted prior to this call.
41  // If match is found, function returns position of element.
42  // If no match found, function gives nearest element smaller than value.
43 
44  int nabove, nbelow, middle;
45  nabove = n + 1;
46  nbelow = 0;
47  while (nabove - nbelow > 1) {
48  middle = (nabove + nbelow) / 2;
49  if (value == array[middle - 1])
50  return middle - 1;
51  if (value < array[middle - 1])
52  nabove = middle;
53  else
54  nbelow = middle;
55  }
56  return nbelow - 1;
57 }
double nEntries
Number of entries.
std::vector< float > integral
Integral.
Definition: value.py:1
int nBins
Pointer to the histogram.
double generate(RandomEngineAndDistribution const *) const
The random generation.
double flatShoot(double xmin=0.0, double xmax=1.0) const
int binarySearch(const int &n, const std::vector< float > &array, const double &value) const