npstat is hosted by Hepforge, IPPP Durham
NPStat  5.10.0
sumOfSquares.hh
Go to the documentation of this file.
1 #ifndef NPSTAT_SUMOFSQUARES_HH_
2 #define NPSTAT_SUMOFSQUARES_HH_
3 
4 /*!
5 // \file sumOfSquares.hh
6 //
7 // \brief A simple code to calculate the sum of squares of elements
8 // inside a contiguous buffer
9 //
10 // Author: I. Volobouev
11 //
12 // November 2020
13 */
14 
15 #include <cassert>
16 
17 #include "npstat/nm/PreciseType.hh"
18 
19 namespace npstat {
20  template<typename Numeric>
21  typename PreciseType<Numeric>::type sumOfSquares(
22  const Numeric* data, const unsigned long len)
23  {
24  typedef typename PreciseType<Numeric>::type Precise;
25  Precise sum = Precise();
26  if (len)
27  {
28  assert(data);
29  for (unsigned long i=0; i<len; ++i)
30  {
31  const Precise v = static_cast<Precise>(data[i]);
32  sum += v*v;
33  }
34  }
35  return sum;
36  }
37 
38 #ifdef SWIG
39  template<typename Numeric>
40  inline double sumOfSquares2(const Numeric* x, const unsigned long xLen)
41  {
42  return sumOfSquares(x, xLen);
43  }
44 #endif // SWIG
45 }
46 
47 #endif // NPSTAT_SUMOFSQUARES_HH_
Compile-time deduction of an appropriate precise numeric type.
Definition: AbsArrayProjector.hh:14