CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
SimpleHistogramGenerator.cc
Go to the documentation of this file.
3 
4 #include <cmath>
5 #include "TH1.h"
6 // #include <iostream>
7 
9  random(engine),
10  myHisto(histo),
11  theXaxis(histo->GetXaxis()),
12  nBins(theXaxis->GetNbins()),
13  xMin(theXaxis->GetXmin()),
14  xMax(theXaxis->GetXmax()),
15  binWidth((xMax-xMin)/(float)nBins)
16 {
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<double>& 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 }
int i
Definition: DBlmapReader.cc:9
double generate() const
The random generation.
double nEntries
Number of entries.
TRandom random
Definition: MVATrainer.cc:138
std::vector< double > integral
Integral.
SimpleHistogramGenerator(TH1 *histo, const RandomEngine *engine)
int binarySearch(const int &n, const std::vector< double > &array, const double &value) const
double flatShoot(double xmin=0.0, double xmax=1.0) const
Definition: RandomEngine.h:30
x
Definition: VDTMath.h:216