Math.hpp 2.11 KB
Newer Older
1
2
#pragma once

3
4
5
6
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <limits>
7
8
#include <type_traits>

9
10
#include <dune/common/power.hh>

11
12
namespace AMDiS
{
13
  namespace Math
14
  {
15
    /// Implementation of the absolute value \f$|a|\f$ of arithmetic types.
16
    template <class T>
17
    constexpr T abs(T const& a)
18
    {
19
      return  a < 0 ? -a : a;
20
    }
21
22


23
    /// Implementation of the square \f$ a^2 \f$ of arithmetic types.
24
    template <class T>
25
    constexpr auto sqr(T const& a)
26
27
28
    {
      return a*a;
    }
29

30
31
    /// Implementation of the power \f$ v^p \f$ of arithmetic types `T`.
    template <int p, class T>
32
    constexpr auto pow(T const& v)
33
    {
34
      static_assert( p >= 0, "Exponent p in `pow<p>(v)` should be >= 0," );
35
      return Dune::Power<p>::eval(v);
36
    }
37

38

39
    /// Implementation of the minimum of values \f$ min(a,b)\f$ of any type
40
41
42
    /// supporting the `<` relation.
    /// @{

43
44
45
    template <class T0, class T1>
    constexpr auto min(T0 a, T1 b)
    {
46
47
      using T = std::conditional_t<(sizeof(T0)>sizeof(T1)),T0,T1>;
      return a < b ? T(a) : T(b);
48
49
50
51
52
53
    }

    template <class T0>
    constexpr T0 min(T0 a)
    {
      return a;
54
    }
55

56
57
58
59
60
61
62
63
    template <class T0, class... Ts>
    constexpr auto min(T0 a, Ts... ts)
    {
      return min(a, min(ts...));
    }

    /// @}

64

65
    /// Implementation of the maximum of values \f$ max(a,b)\f$ of any type
66
    /// supporting the `<` relation.
67
    /// @{
68

69
70
71
    template <class T0, class T1>
    constexpr auto max(T0 a, T1 b)
    {
72
73
      using T = std::conditional_t<(sizeof(T0)>sizeof(T1)),T0,T1>;
      return a < b ? T(b) : T(a);
74
75
76
77
78
79
    }

    template <class T0>
    constexpr T0 max(T0 a)
    {
      return a;
80
    }
81

82
83
84
85
86
87
88
89
    template <class T0, class... Ts>
    constexpr auto max(T0 a, Ts... ts)
    {
      return max(a, max(ts...));
    }

    /// @}

90
91
92
93
94
    // sum over empty set is zero
    constexpr double sum()
    {
      return 0.0;
    }
95

96
97
98
99
100
101
102
    template <class... Ts>
    constexpr auto sum(Ts const&... ts)
    {
      return (ts + ...);
    }

  } // end namespace Math
103

104
  template <class T>
105
  constexpr T threshold = std::numeric_limits<T>::epsilon();
106

107
} // end namespace AMDiS