Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
utils.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
17
18namespace shamunits::details {
19
21 template<int power, class T>
22 inline constexpr T pow_constexpr_fast_inv(T a, T a_inv) noexcept {
23
24 if constexpr (power < 0) {
25 return pow_constexpr_fast_inv<-power>(a_inv, a);
26 } else if constexpr (power == 0) {
27 return T{1};
28 } else if constexpr (power % 2 == 0) {
29 T tmp = pow_constexpr_fast_inv<power / 2>(a, a_inv);
30 return tmp * tmp;
31 } else if constexpr (power % 2 == 1) {
32 T tmp = pow_constexpr_fast_inv<(power - 1) / 2>(a, a_inv);
33 return tmp * tmp * a;
34 }
35 }
36
44 template<class T>
45 inline constexpr T ipow(T a, int n, T a_inv) noexcept {
46 T base = (n < 0) ? a_inv : a;
47 unsigned k = (n < 0) ? 0u - static_cast<unsigned>(n) : static_cast<unsigned>(n);
48
49 int top_bit = -1;
50 for (unsigned t = k; t != 0; t >>= 1) {
51 ++top_bit;
52 }
53
54 T res = T{1};
55 for (int b = top_bit; b >= 0; --b) {
56 res = res * res;
57 if (((k >> b) & 1u) != 0) {
58 res = res * base;
59 }
60 }
61 return res;
62 }
63} // namespace shamunits::details
constexpr T pow_constexpr_fast_inv(T a, T a_inv) noexcept
Constexpr power expansion function with supplied inverse for negative values.
Definition utils.hpp:22
constexpr T ipow(T a, int n, T a_inv) noexcept
Runtime twin of pow_constexpr_fast_inv, for an exponent only known at run time.
Definition utils.hpp:45