NumericUtils.h
Go to the documentation of this file.
1 /**
2  * @file larcorealg/CoreUtils/NumericUtils.h
3  * @brief Functions to help with numbers.
4  * @author Gianluca Petrillo (petrillo@fnal.gov)
5  * @date March 30, 2018
6  *
7  * This library is currently header-only.
8  */
9 #ifndef LARCOREALG_COREUTILS_NUMERICUTILS_H
10 #define LARCOREALG_COREUTILS_NUMERICUTILS_H
11 
12 // C/C++ standard libraries
13 #include <type_traits>
14 
15 
16 namespace util {
17 
18  // @{
19  /**
20  * @brief Returns the absolute value of the difference between two values.
21  * @tparam A type of the first value
22  * @tparam B type of the second value (*must* actually be as `A`)
23  * @param a the first value
24  * @param b the second value
25  * @return the difference between the largest and the smallest of `a` and `b`
26  *
27  * The pecularity of this implementation is that it always avoids taking the
28  * difference between the smallest and the largest of `a` and `b`. An
29  * equivalent implementation is:
30  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
31  * return std::max(a, b) - std::min(a, b);
32  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
33  *
34  * It still assumes that the difference is representable in `A`; for example,
35  * this assumption will fail for `int` types with `a` a very large number and
36  * `b` a very small (i.e. negative) number.
37  *
38  * Requirements:
39  * * `A` and `B` must be the same type
40  *
41  */
42  template <typename A, typename B>
43  constexpr auto absDiff(A const& a, B const& b)
44  {
45  static_assert(
46  std::is_same<std::decay_t<A>, std::decay_t<B>>(),
47  "Arguments of util::absDiff() have to be of the same type."
48  );
49  return (b > a)? (b - a): (a - b);
50  }
51  // @}
52 
53 } // namespace util
54 
55 
56 #endif // LARCOREALG_COREUTILS_NUMERICUTILS_H
57 
Namespace for general, non-LArSoft-specific utilities.
const double a
constexpr auto absDiff(A const &a, B const &b)
Returns the absolute value of the difference between two values.
Definition: NumericUtils.h:43
static bool * b
Definition: config.cpp:1043