dune-common  2.11
cmath.hh
Go to the documentation of this file.
1 // -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 // vi: set et ts=4 sw=2 sts=2:
3 // SPDX-FileCopyrightInfo: Copyright © DUNE Project contributors, see file LICENSE.md in module root
4 // SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception
5 #ifndef DUNE_COMMON_STD_CMATH_HH
6 #define DUNE_COMMON_STD_CMATH_HH
7 
8 #include <cmath>
9 
10 #if __has_include(<version>)
11 #include <version>
12 #if (__cpp_lib_constexpr_cmath < 202306L)
13 #include <limits>
14 #include <type_traits>
15 #include <utility>
16 #endif
17 #endif
18 
19 namespace Dune {
20 
21 namespace Std {
22 
23 #if (__cpp_lib_constexpr_cmath < 202202L)
24 // backport for constexpr functions between C++20 and C++23
25 template<class T>
26 constexpr T
27 abs(T t)
28 {
29  if (std::is_constant_evaluated()) {
30  return (t < 0) ? -t : t;
31  } else {
32  using std::abs;
33  return abs(t);
34  }
35 }
36 
37 template<class T>
38 constexpr auto
39 sqrt(T t)
40  requires(std::is_floating_point_v<T> || std::is_integral_v<T>)
41 {
42  if (std::is_constant_evaluated()) {
43  using TT = std::conditional_t<std::is_floating_point_v<T>, T, double>;
44  if (t >= TT{ 0 } and t < std::numeric_limits<TT>::infinity()) {
45  // use Heron's method:
46  // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Heron's_method
47  TT curr = t, prev = 0;
48  while (curr != prev)
49  prev = std::exchange(curr, TT{ 0.5 } * (curr + TT{ t } / curr));
50  return curr;
51  } else {
52  return std::numeric_limits<TT>::quiet_NaN();
53  }
54  } else {
55  using std::sqrt;
56  return sqrt(t);
57  }
58 };
59 #else
60 using std::abs;
61 using std::sqrt;
62 #endif
63 
64 } // namespace Std
65 
66 } // namespace Dune
67 
68 #endif // #ifndef DUNE_COMMON_STD_CMATH_HH
requires(((std::is_integral_v< I > or Dune::IsIntegralConstant< I >::value) &&...)) HybridMultiIndex(I... i) -> HybridMultiIndex< decltype(Impl::castToHybridSizeT(i))... >
Dune namespace
Definition: alignedallocator.hh:12
constexpr auto sqrt(T t) requires(std
Definition: cmath.hh:39
constexpr T abs(T t)
Definition: cmath.hh:27