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