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

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

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

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


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

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

39

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

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

    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 two values \f$ max(a,b)\f$ of any type
66
    /// supporting the `>` relation.
67
    /// @{
68
69
70
    template <class T0, class T1>
    constexpr auto max(T0 a, T1 b)
    {
71
72
73
74
75
76
77
      return a < b ? b : a;
    }

    template <class T0>
    constexpr T0 max(T0 a)
    {
      return a;
78
    }
79

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

    /// @}

88
  } // end namespace Math
89
90


91
92
  template <class T>
  inline void nullify(T& a)
93
94
95
  {
    a = 0;
  }
96

97
98
99
100
  inline void nullify(std::string& s)
  {
    s = "";
  }
101

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


106
  /// Calculates factorial of i
107
  constexpr std::uint64_t factorial(std::uint64_t i)
108
109
110
  {
    return i <= 1 ? 1 : i * factorial(i - 1);
  }
111

112
113
114
115
116
  /// check for inf and nan values
  inline bool isNumber(double val)
  {
    return !std::isnan(val) && !std::isinf(val);
  }
117
118

} // end namespace AMDiS