npstat is hosted by Hepforge, IPPP Durham
NPStat  5.10.0
resampleWithReplacement.hh
Go to the documentation of this file.
1 #ifndef NPSTAT_RESAMPLEWITHREPLACEMENT_HH_
2 #define NPSTAT_RESAMPLEWITHREPLACEMENT_HH_
3 
4 /*!
5 // \file resampleWithReplacement.hh
6 //
7 // \brief Resampling with replacement from a vector of points
8 //
9 // Author: I. Volobouev
10 //
11 // May 2022
12 */
13 
14 #include <vector>
15 #include <cassert>
16 #include <stdexcept>
17 
19 
20 namespace npstat {
21  /**
22  // On output, vector "to" will be filled by a random sample
23  // of elements of the vector "from", chosen with replacement,
24  // according to the sample size requested. Note that, due to
25  // the simplicity of the algorithm and for very large "from"
26  // vectors, discreteness of random doubles on [0, 1) can affect
27  // resampling uniformity.
28  */
29  template<typename T>
31  const std::vector<T>& from,
32  std::vector<T>* to,
33  const unsigned long sampleSizeWanted)
34  {
35  const unsigned long sz = from.size();
36  if (!sz) throw std::invalid_argument(
37  "In npstat::resampleWithReplacement: empty input sample");
38  const double dsz = sz;
39 
40  assert(to);
41  to->clear();
42  to->reserve(sampleSizeWanted);
43 
44  for (unsigned long i=0; i<sampleSizeWanted; ++i)
45  {
46  unsigned long idx = sz;
47  while (idx >= sz)
48  idx = static_cast<unsigned long>(dsz*gen());
49  to->push_back(from[idx]);
50  }
51  }
52 
53 #ifdef SWIG
54  template<typename T>
55  inline std::vector<T> resampleWithReplacement2(
56  AbsRandomGenerator& gen, const std::vector<T>& from,
57  const unsigned long sampleSizeWanted)
58  {
59  std::vector<T> to;
60  resampleWithReplacement(gen, from, &to, sampleSizeWanted);
61  return to;
62  }
63 #endif
64 }
65 
66 #endif // NPSTAT_RESAMPLEWITHREPLACEMENT_HH_
Interface definition for pseudo- and quasi-random number generators.
Definition: AbsArrayProjector.hh:14
void resampleWithReplacement(AbsRandomGenerator &gen, const std::vector< T > &from, std::vector< T > *to, const unsigned long sampleSizeWanted)
Definition: resampleWithReplacement.hh:30
Definition: AbsRandomGenerator.hh:27