ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
periodic_fold.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2010-2022 The ESPResSo project
3 *
4 * This file is part of ESPResSo.
5 *
6 * ESPResSo is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * ESPResSo is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19#ifndef CORE_ALGORITHM_PERIODIC_FOLD_HPP
20#define CORE_ALGORITHM_PERIODIC_FOLD_HPP
21
22#include <cmath>
23#include <limits>
24#include <utility>
25
26namespace Algorithm {
27/**
28 * @brief Fold value into primary interval.
29 *
30 * @param x Value to fold
31 * @param i Image count before folding
32 * @param l Length of primary interval
33 * @return x folded into [0, l) and number of folds.
34 */
35template <typename T, typename I>
36std::pair<T, I> periodic_fold(T x, I i, T const l) {
37 using limits = std::numeric_limits<I>;
38
39 while ((x < T{0}) && (i > limits::min())) {
40 x += l;
41 --i;
42 }
43
44 while ((x >= l) && (i < limits::max())) {
45 x -= l;
46 ++i;
47 }
48
49 return {x, i};
50}
51
52/**
53 * @brief Fold value into primary interval.
54 *
55 * @param x Value to fold
56 * @param l Length of primary interval
57 * @return x folded into [0, l).
58 */
59template <typename T> T periodic_fold(T x, T const l) {
60#ifndef __FAST_MATH__
61 /* Can't fold if either x or l is nan or inf. */
62 if (std::isnan(x) or std::isnan(l) or std::isinf(x) or (l == 0)) {
63 return std::nan("");
64 }
65 if (std::isinf(l)) {
66 return x;
67 }
68#endif // __FAST_MATH__
69
70 while (x < 0) {
71 x += l;
72 }
73
74 while (x >= l) {
75 x -= l;
76 }
77
78 return x;
79}
80} // namespace Algorithm
81
82#endif
std::pair< T, I > periodic_fold(T x, I i, T const l)
Fold value into primary interval.