DDC 0.1.0
Loading...
Searching...
No Matches
math_tools.hpp
1// Copyright (C) The DDC development team, see COPYRIGHT.md file
2//
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
7#include <array>
8#include <cmath>
9#include <cstddef>
10
11#include <Kokkos_Core.hpp>
12
13namespace ddc::detail {
14
15template <typename T>
16KOKKOS_INLINE_FUNCTION T sum(T* array, int size)
17{
18 T val(0.0);
19 for (int i(0); i < size; ++i) {
20 val += array[i];
21 }
22 return val;
23}
24
25template <class ElementType, class LayoutPolicy, class AccessorPolicy, std::size_t Ext>
26KOKKOS_INLINE_FUNCTION ElementType sum(Kokkos::mdspan<
27 ElementType,
28 Kokkos::extents<std::size_t, Ext>,
29 LayoutPolicy,
30 AccessorPolicy> const& array)
31{
32 ElementType val(0.0);
33 for (std::size_t i(0); i < array.extent(0); ++i) {
34 val += array[i];
35 }
36 return val;
37}
38
39template <class ElementType, class LayoutPolicy, class AccessorPolicy, std::size_t Ext>
40KOKKOS_INLINE_FUNCTION ElementType
41sum(Kokkos::mdspan<
42 ElementType,
43 Kokkos::extents<std::size_t, Ext>,
44 LayoutPolicy,
45 AccessorPolicy> const& array,
46 int start,
47 int end)
48{
49 ElementType val(0.0);
50 for (int i(start); i < end; ++i) {
51 val += array[i];
52 }
53 return val;
54}
55
56template <typename T>
57KOKKOS_INLINE_FUNCTION T modulo(T x, T y)
58{
59 return x - y * Kokkos::floor(double(x) / y);
60}
61
62KOKKOS_INLINE_FUNCTION double ipow(double a, std::size_t i)
63{
64 double r(1.0);
65 for (std::size_t j(0); j < i; ++j) {
66 r *= a;
67 }
68 return r;
69}
70
71KOKKOS_INLINE_FUNCTION double ipow(double a, int i)
72{
73 double r(1.0);
74 if (i > 0) {
75 for (int j(0); j < i; ++j) {
76 r *= a;
77 }
78 } else if (i < 0) {
79 for (int j(0); j < -i; ++j) {
80 r *= a;
81 }
82 r = 1.0 / r;
83 }
84 return r;
85}
86
87KOKKOS_INLINE_FUNCTION std::size_t factorial(std::size_t f)
88{
89 std::size_t r = 1;
90 for (std::size_t i(2); i < f + 1; ++i) {
91 r *= i;
92 }
93 return r;
94}
95
96template <class T, std::size_t D>
97KOKKOS_INLINE_FUNCTION T dot_product(std::array<T, D> const& a, std::array<T, D> const& b)
98{
99 T result = 0;
100 for (std::size_t i(0); i < D; ++i) {
101 result += a[i] * b[i];
102 }
103 return result;
104}
105
106template <typename T>
107KOKKOS_INLINE_FUNCTION T min(T x, T y)
108{
109 return x < y ? x : y;
110}
111
112template <typename T>
113KOKKOS_INLINE_FUNCTION T max(T x, T y)
114{
115 return x > y ? x : y;
116}
117
118} // namespace ddc::detail
The top-level namespace of DDC.