yat  0.21pre
round.h
1 #ifndef _theplu_yat_utility_round_
2 #define _theplu_yat_utility_round_
3 
4 // $Id: round.h 4059 2021-04-20 02:28:38Z peter $
5 
6 /*
7  Copyright (C) 2021 Peter Johansson
8 
9  This file is part of the yat library, http://dev.thep.lu.se/yat
10 
11  The yat library is free software; you can redistribute it and/or
12  modify it under the terms of the GNU General Public License as
13  published by the Free Software Foundation; either version 3 of the
14  License, or (at your option) any later version.
15 
16  The yat library is distributed in the hope that it will be useful,
17  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  General Public License for more details.
20 
21  You should have received a copy of the GNU General Public License
22  along with yat. If not, see <http://www.gnu.org/licenses/>.
23 */
24 
25 #include <cmath>
26 #include <map>
27 
28 namespace theplu {
29 namespace yat {
30 namespace utility {
31 
46  template<typename InputIterator, typename ForwardIterator>
47  void round(InputIterator first, InputIterator last,
48  ForwardIterator result)
49  {
50  std::multimap<double, ForwardIterator> map;
51  double result_sum = 0;
52  double input_sum = 0;
53  for (auto it = first; it != last; ++it) {
54  // copy value here in case result and first point to same value
55  double x = *it;
56  input_sum += x;
57  *result = std::floor(x);
58  map.insert(std::make_pair(*result - x, result));
59  result_sum += *result;
60  ++result;
61  }
62  double rounded_sum = std::round(input_sum);
63 
64  for (auto it = map.begin(); result_sum<rounded_sum; ++it) {
65  YAT_ASSERT(it != map.end());
66  *it->second += 1.0;
67  result_sum += 1.0;
68  }
69  }
70 
71 }}} // of namespace utility, yat, and theplu
72 
73 #endif
The Department of Theoretical Physics namespace as we define it.
void round(InputIterator first, InputIterator last, ForwardIterator result)
Round a range.
Definition: round.h:47

Generated on Wed Jan 25 2023 03:34:29 for yat by  doxygen 1.8.14