1 // <numeric> -*- C++ -*-
3 // Copyright (C) 2001-2020 Free Software Foundation, Inc.
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
11 // This library 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.
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
28 * Hewlett-Packard Company
30 * Permission to use, copy, modify, distribute and sell this software
31 * and its documentation for any purpose is hereby granted without fee,
32 * provided that the above copyright notice appear in all copies and
33 * that both that copyright notice and this permission notice appear
34 * in supporting documentation. Hewlett-Packard Company makes no
35 * representations about the suitability of this software for any
36 * purpose. It is provided "as is" without express or implied warranty.
39 * Copyright (c) 1996,1997
40 * Silicon Graphics Computer Systems, Inc.
42 * Permission to use, copy, modify, distribute and sell this software
43 * and its documentation for any purpose is hereby granted without fee,
44 * provided that the above copyright notice appear in all copies and
45 * that both that copyright notice and this permission notice appear
46 * in supporting documentation. Silicon Graphics makes no
47 * representations about the suitability of this software for any
48 * purpose. It is provided "as is" without express or implied warranty.
51 /** @file include/numeric
52 * This is a Standard C++ Library header.
55 #ifndef _GLIBCXX_NUMERIC
56 #define _GLIBCXX_NUMERIC 1
58 #pragma GCC system_header
60 #include <bits/c++config.h>
61 #include <bits/stl_iterator_base_types.h>
62 #include <bits/stl_numeric.h>
64 #ifdef _GLIBCXX_PARALLEL
65 # include <parallel/numeric>
69 * @defgroup numerics Numerics
71 * Components for performing numeric operations. Includes support for
72 * complex number types, random number generation, numeric (n-at-a-time)
73 * arrays, generalized numeric algorithms, and mathematical special functions.
76 #if __cplusplus >= 201402L
77 #include <type_traits>
79 namespace std _GLIBCXX_VISIBILITY(default)
81 _GLIBCXX_BEGIN_NAMESPACE_VERSION
85 // std::abs is not constexpr and doesn't support unsigned integers.
86 template<typename _Tp>
88 enable_if_t<__and_<is_integral<_Tp>, is_signed<_Tp>>::value, _Tp>
89 __abs_integral(_Tp __val)
90 { return __val < 0 ? -__val : __val; }
92 template<typename _Tp>
94 enable_if_t<__and_<is_integral<_Tp>, is_unsigned<_Tp>>::value, _Tp>
95 __abs_integral(_Tp __val)
98 void __abs_integral(bool) = delete;
100 template<typename _Mn, typename _Nn>
101 constexpr common_type_t<_Mn, _Nn>
102 __gcd(_Mn __m, _Nn __n)
104 return __m == 0 ? __detail::__abs_integral(__n)
105 : __n == 0 ? __detail::__abs_integral(__m)
106 : __detail::__gcd(__n, __m % __n);
109 /// Least common multiple
110 template<typename _Mn, typename _Nn>
111 constexpr common_type_t<_Mn, _Nn>
112 __lcm(_Mn __m, _Nn __n)
114 return (__m != 0 && __n != 0)
115 ? (__detail::__abs_integral(__m) / __detail::__gcd(__m, __n))
116 * __detail::__abs_integral(__n)
119 } // namespace __detail
121 #if __cplusplus >= 201703L
123 #define __cpp_lib_gcd_lcm 201606
124 // These were used in drafts of SD-6:
125 #define __cpp_lib_gcd 201606
126 #define __cpp_lib_lcm 201606
128 /// Greatest common divisor
129 template<typename _Mn, typename _Nn>
130 constexpr common_type_t<_Mn, _Nn>
131 gcd(_Mn __m, _Nn __n)
133 static_assert(is_integral_v<_Mn>, "gcd arguments are integers");
134 static_assert(is_integral_v<_Nn>, "gcd arguments are integers");
135 static_assert(!is_same_v<remove_cv_t<_Mn>, bool>,
136 "gcd arguments are not bools");
137 static_assert(!is_same_v<remove_cv_t<_Nn>, bool>,
138 "gcd arguments are not bools");
139 return __detail::__gcd(__m, __n);
142 /// Least common multiple
143 template<typename _Mn, typename _Nn>
144 constexpr common_type_t<_Mn, _Nn>
145 lcm(_Mn __m, _Nn __n)
147 static_assert(is_integral_v<_Mn>, "lcm arguments are integers");
148 static_assert(is_integral_v<_Nn>, "lcm arguments are integers");
149 static_assert(!is_same_v<remove_cv_t<_Mn>, bool>,
150 "lcm arguments are not bools");
151 static_assert(!is_same_v<remove_cv_t<_Nn>, bool>,
152 "lcm arguments are not bools");
153 return __detail::__lcm(__m, __n);
158 _GLIBCXX_END_NAMESPACE_VERSION
163 #if __cplusplus > 201703L
166 namespace std _GLIBCXX_VISIBILITY(default)
168 _GLIBCXX_BEGIN_NAMESPACE_VERSION
170 # define __cpp_lib_interpolate 201902L
172 template<typename _Tp>
174 enable_if_t<__and_v<is_arithmetic<_Tp>, is_same<remove_cv_t<_Tp>, _Tp>,
175 __not_<is_same<_Tp, bool>>>,
177 midpoint(_Tp __a, _Tp __b) noexcept
179 if constexpr (is_integral_v<_Tp>)
181 using _Up = make_unsigned_t<_Tp>;
192 return __a + __k * _Tp(_Up(__M - __m) / 2);
196 constexpr _Tp __lo = numeric_limits<_Tp>::min() * 2;
197 constexpr _Tp __hi = numeric_limits<_Tp>::max() / 2;
198 const _Tp __abs_a = __a < 0 ? -__a : __a;
199 const _Tp __abs_b = __b < 0 ? -__b : __b;
200 if (__abs_a <= __hi && __abs_b <= __hi) [[likely]]
201 return (__a + __b) / 2; // always correctly rounded
202 if (__abs_a < __lo) // not safe to halve __a
204 if (__abs_b < __lo) // not safe to halve __b
206 return __a/2 + __b/2; // otherwise correctly rounded
210 template<typename _Tp>
211 constexpr enable_if_t<is_object_v<_Tp>, _Tp*>
212 midpoint(_Tp* __a, _Tp* __b) noexcept
214 static_assert( sizeof(_Tp) != 0, "type must be complete" );
215 return __a + (__b - __a) / 2;
217 _GLIBCXX_END_NAMESPACE_VERSION
222 #if __cplusplus > 201402L
223 #include <bits/stl_function.h>
225 namespace std _GLIBCXX_VISIBILITY(default)
227 _GLIBCXX_BEGIN_NAMESPACE_VERSION
229 #if __cplusplus > 201703L
230 #define __cpp_lib_constexpr_numeric 201911L
233 /// @addtogroup numeric_ops
237 * @brief Calculate reduction of values in a range.
239 * @param __first Start of range.
240 * @param __last End of range.
241 * @param __init Starting value to add other values to.
242 * @param __binary_op A binary function object.
243 * @return The final sum.
245 * Reduce the values in the range `[first,last)` using a binary operation.
246 * The initial value is `init`. The values are not necessarily processed
249 * This algorithm is similar to `std::accumulate` but is not required to
250 * perform the operations in order from first to last. For operations
251 * that are commutative and associative the result will be the same as
252 * for `std::accumulate`, but for other operations (such as floating point
253 * arithmetic) the result can be different.
255 template<typename _InputIterator, typename _Tp, typename _BinaryOperation>
258 reduce(_InputIterator __first, _InputIterator __last, _Tp __init,
259 _BinaryOperation __binary_op)
261 using value_type = typename iterator_traits<_InputIterator>::value_type;
262 static_assert(is_invocable_r_v<_Tp, _BinaryOperation&, _Tp&, _Tp&>);
263 static_assert(is_convertible_v<value_type, _Tp>);
264 if constexpr (__is_random_access_iter<_InputIterator>::value)
266 while ((__last - __first) >= 4)
268 _Tp __v1 = __binary_op(__first[0], __first[1]);
269 _Tp __v2 = __binary_op(__first[2], __first[3]);
270 _Tp __v3 = __binary_op(__v1, __v2);
271 __init = __binary_op(__init, __v3);
275 for (; __first != __last; ++__first)
276 __init = __binary_op(__init, *__first);
281 * @brief Calculate reduction of values in a range.
283 * @param __first Start of range.
284 * @param __last End of range.
285 * @param __init Starting value to add other values to.
286 * @return The final sum.
288 * Reduce the values in the range `[first,last)` using addition.
289 * Equivalent to calling `std::reduce(first, last, init, std::plus<>())`.
291 template<typename _InputIterator, typename _Tp>
294 reduce(_InputIterator __first, _InputIterator __last, _Tp __init)
295 { return std::reduce(__first, __last, std::move(__init), plus<>()); }
298 * @brief Calculate reduction of values in a range.
300 * @param __first Start of range.
301 * @param __last End of range.
302 * @return The final sum.
304 * Reduce the values in the range `[first,last)` using addition, with
305 * an initial value of `T{}`, where `T` is the iterator's value type.
306 * Equivalent to calling `std::reduce(first, last, T{}, std::plus<>())`.
308 template<typename _InputIterator>
310 inline typename iterator_traits<_InputIterator>::value_type
311 reduce(_InputIterator __first, _InputIterator __last)
313 using value_type = typename iterator_traits<_InputIterator>::value_type;
314 return std::reduce(__first, __last, value_type{}, plus<>());
318 * @brief Combine elements from two ranges and reduce
320 * @param __first1 Start of first range.
321 * @param __last1 End of first range.
322 * @param __first2 Start of second range.
323 * @param __init Starting value to add other values to.
324 * @param __binary_op1 The function used to perform reduction.
325 * @param __binary_op2 The function used to combine values from the ranges.
326 * @return The final sum.
328 * Call `binary_op2(first1[n],first2[n])` for each `n` in `[0,last1-first1)`
329 * and then use `binary_op1` to reduce the values returned by `binary_op2`
330 * to a single value of type `T`.
332 * The range beginning at `first2` must contain at least `last1-first1`
335 template<typename _InputIterator1, typename _InputIterator2, typename _Tp,
336 typename _BinaryOperation1, typename _BinaryOperation2>
339 transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1,
340 _InputIterator2 __first2, _Tp __init,
341 _BinaryOperation1 __binary_op1,
342 _BinaryOperation2 __binary_op2)
344 if constexpr (__and_v<__is_random_access_iter<_InputIterator1>,
345 __is_random_access_iter<_InputIterator2>>)
347 while ((__last1 - __first1) >= 4)
349 _Tp __v1 = __binary_op1(__binary_op2(__first1[0], __first2[0]),
350 __binary_op2(__first1[1], __first2[1]));
351 _Tp __v2 = __binary_op1(__binary_op2(__first1[2], __first2[2]),
352 __binary_op2(__first1[3], __first2[3]));
353 _Tp __v3 = __binary_op1(__v1, __v2);
354 __init = __binary_op1(__init, __v3);
359 for (; __first1 != __last1; ++__first1, (void) ++__first2)
360 __init = __binary_op1(__init, __binary_op2(*__first1, *__first2));
365 * @brief Combine elements from two ranges and reduce
367 * @param __first1 Start of first range.
368 * @param __last1 End of first range.
369 * @param __first2 Start of second range.
370 * @param __init Starting value to add other values to.
371 * @return The final sum.
373 * Call `first1[n]*first2[n]` for each `n` in `[0,last1-first1)` and then
374 * use addition to sum those products to a single value of type `T`.
376 * The range beginning at `first2` must contain at least `last1-first1`
379 template<typename _InputIterator1, typename _InputIterator2, typename _Tp>
382 transform_reduce(_InputIterator1 __first1, _InputIterator1 __last1,
383 _InputIterator2 __first2, _Tp __init)
385 return std::transform_reduce(__first1, __last1, __first2,
387 plus<>(), multiplies<>());
391 * @brief Transform the elements of a range and reduce
393 * @param __first Start of range.
394 * @param __last End of range.
395 * @param __init Starting value to add other values to.
396 * @param __binary_op The function used to perform reduction.
397 * @param __unary_op The function used to transform values from the range.
398 * @return The final sum.
400 * Call `unary_op(first[n])` for each `n` in `[0,last-first)` and then
401 * use `binary_op` to reduce the values returned by `unary_op`
402 * to a single value of type `T`.
404 template<typename _InputIterator, typename _Tp,
405 typename _BinaryOperation, typename _UnaryOperation>
408 transform_reduce(_InputIterator __first, _InputIterator __last, _Tp __init,
409 _BinaryOperation __binary_op, _UnaryOperation __unary_op)
411 if constexpr (__is_random_access_iter<_InputIterator>::value)
413 while ((__last - __first) >= 4)
415 _Tp __v1 = __binary_op(__unary_op(__first[0]),
416 __unary_op(__first[1]));
417 _Tp __v2 = __binary_op(__unary_op(__first[2]),
418 __unary_op(__first[3]));
419 _Tp __v3 = __binary_op(__v1, __v2);
420 __init = __binary_op(__init, __v3);
424 for (; __first != __last; ++__first)
425 __init = __binary_op(__init, __unary_op(*__first));
429 /** @brief Output the cumulative sum of one range to a second range
431 * @param __first Start of input range.
432 * @param __last End of input range.
433 * @param __result Start of output range.
434 * @param __init Initial value.
435 * @param __binary_op Function to perform summation.
436 * @return The end of the output range.
438 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
439 * to the output range. Each element of the output range contains the
440 * running total of all earlier elements (and the initial value),
441 * using `binary_op` for summation.
443 * This function generates an "exclusive" scan, meaning the Nth element
444 * of the output range is the sum of the first N-1 input elements,
445 * so the Nth input element is not included.
447 template<typename _InputIterator, typename _OutputIterator, typename _Tp,
448 typename _BinaryOperation>
451 exclusive_scan(_InputIterator __first, _InputIterator __last,
452 _OutputIterator __result, _Tp __init,
453 _BinaryOperation __binary_op)
455 while (__first != __last)
458 __init = __binary_op(__init, *__first);
460 *__result++ = std::move(__v);
465 /** @brief Output the cumulative sum of one range to a second range
467 * @param __first Start of input range.
468 * @param __last End of input range.
469 * @param __result Start of output range.
470 * @param __init Initial value.
471 * @return The end of the output range.
473 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
474 * to the output range. Each element of the output range contains the
475 * running total of all earlier elements (and the initial value),
476 * using `std::plus<>` for summation.
478 * This function generates an "exclusive" scan, meaning the Nth element
479 * of the output range is the sum of the first N-1 input elements,
480 * so the Nth input element is not included.
482 template<typename _InputIterator, typename _OutputIterator, typename _Tp>
484 inline _OutputIterator
485 exclusive_scan(_InputIterator __first, _InputIterator __last,
486 _OutputIterator __result, _Tp __init)
488 return std::exclusive_scan(__first, __last, __result, std::move(__init),
492 /** @brief Output the cumulative sum of one range to a second range
494 * @param __first Start of input range.
495 * @param __last End of input range.
496 * @param __result Start of output range.
497 * @param __binary_op Function to perform summation.
498 * @param __init Initial value.
499 * @return The end of the output range.
501 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
502 * to the output range. Each element of the output range contains the
503 * running total of all earlier elements (and the initial value),
504 * using `binary_op` for summation.
506 * This function generates an "inclusive" scan, meaning the Nth element
507 * of the output range is the sum of the first N input elements,
508 * so the Nth input element is included.
510 template<typename _InputIterator, typename _OutputIterator,
511 typename _BinaryOperation, typename _Tp>
514 inclusive_scan(_InputIterator __first, _InputIterator __last,
515 _OutputIterator __result, _BinaryOperation __binary_op,
518 for (; __first != __last; ++__first)
519 *__result++ = __init = __binary_op(__init, *__first);
523 /** @brief Output the cumulative sum of one range to a second range
525 * @param __first Start of input range.
526 * @param __last End of input range.
527 * @param __result Start of output range.
528 * @param __binary_op Function to perform summation.
529 * @return The end of the output range.
531 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
532 * to the output range. Each element of the output range contains the
533 * running total of all earlier elements, using `binary_op` for summation.
535 * This function generates an "inclusive" scan, meaning the Nth element
536 * of the output range is the sum of the first N input elements,
537 * so the Nth input element is included.
539 template<typename _InputIterator, typename _OutputIterator,
540 typename _BinaryOperation>
543 inclusive_scan(_InputIterator __first, _InputIterator __last,
544 _OutputIterator __result, _BinaryOperation __binary_op)
546 if (__first != __last)
548 auto __init = *__first;
549 *__result++ = __init;
551 if (__first != __last)
552 __result = std::inclusive_scan(__first, __last, __result,
553 __binary_op, std::move(__init));
558 /** @brief Output the cumulative sum of one range to a second range
560 * @param __first Start of input range.
561 * @param __last End of input range.
562 * @param __result Start of output range.
563 * @return The end of the output range.
565 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
566 * to the output range. Each element of the output range contains the
567 * running total of all earlier elements, using `std::plus<>` for summation.
569 * This function generates an "inclusive" scan, meaning the Nth element
570 * of the output range is the sum of the first N input elements,
571 * so the Nth input element is included.
573 template<typename _InputIterator, typename _OutputIterator>
575 inline _OutputIterator
576 inclusive_scan(_InputIterator __first, _InputIterator __last,
577 _OutputIterator __result)
578 { return std::inclusive_scan(__first, __last, __result, plus<>()); }
580 /** @brief Output the cumulative sum of one range to a second range
582 * @param __first Start of input range.
583 * @param __last End of input range.
584 * @param __result Start of output range.
585 * @param __init Initial value.
586 * @param __binary_op Function to perform summation.
587 * @param __unary_op Function to transform elements of the input range.
588 * @return The end of the output range.
590 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
591 * to the output range. Each element of the output range contains the
592 * running total of all earlier elements (and the initial value),
593 * using `__unary_op` to transform the input elements
594 * and using `__binary_op` for summation.
596 * This function generates an "exclusive" scan, meaning the Nth element
597 * of the output range is the sum of the first N-1 input elements,
598 * so the Nth input element is not included.
600 template<typename _InputIterator, typename _OutputIterator, typename _Tp,
601 typename _BinaryOperation, typename _UnaryOperation>
604 transform_exclusive_scan(_InputIterator __first, _InputIterator __last,
605 _OutputIterator __result, _Tp __init,
606 _BinaryOperation __binary_op,
607 _UnaryOperation __unary_op)
609 while (__first != __last)
612 __init = __binary_op(__init, __unary_op(*__first));
614 *__result++ = std::move(__v);
619 /** @brief Output the cumulative sum of one range to a second range
621 * @param __first Start of input range.
622 * @param __last End of input range.
623 * @param __result Start of output range.
624 * @param __binary_op Function to perform summation.
625 * @param __unary_op Function to transform elements of the input range.
626 * @param __init Initial value.
627 * @return The end of the output range.
629 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
630 * to the output range. Each element of the output range contains the
631 * running total of all earlier elements (and the initial value),
632 * using `__unary_op` to transform the input elements
633 * and using `__binary_op` for summation.
635 * This function generates an "inclusive" scan, meaning the Nth element
636 * of the output range is the sum of the first N input elements,
637 * so the Nth input element is included.
639 template<typename _InputIterator, typename _OutputIterator,
640 typename _BinaryOperation, typename _UnaryOperation, typename _Tp>
643 transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
644 _OutputIterator __result,
645 _BinaryOperation __binary_op,
646 _UnaryOperation __unary_op,
649 for (; __first != __last; ++__first)
650 *__result++ = __init = __binary_op(__init, __unary_op(*__first));
654 /** @brief Output the cumulative sum of one range to a second range
656 * @param __first Start of input range.
657 * @param __last End of input range.
658 * @param __result Start of output range.
659 * @param __binary_op Function to perform summation.
660 * @param __unary_op Function to transform elements of the input range.
661 * @return The end of the output range.
663 * Write the cumulative sum (aka prefix sum, aka scan) of the input range
664 * to the output range. Each element of the output range contains the
665 * running total of all earlier elements,
666 * using `__unary_op` to transform the input elements
667 * and using `__binary_op` for summation.
669 * This function generates an "inclusive" scan, meaning the Nth element
670 * of the output range is the sum of the first N input elements,
671 * so the Nth input element is included.
673 template<typename _InputIterator, typename _OutputIterator,
674 typename _BinaryOperation, typename _UnaryOperation>
677 transform_inclusive_scan(_InputIterator __first, _InputIterator __last,
678 _OutputIterator __result,
679 _BinaryOperation __binary_op,
680 _UnaryOperation __unary_op)
682 if (__first != __last)
684 auto __init = __unary_op(*__first);
685 *__result++ = __init;
687 if (__first != __last)
688 __result = std::transform_inclusive_scan(__first, __last, __result,
689 __binary_op, __unary_op,
695 // @} group numeric_ops
697 _GLIBCXX_END_NAMESPACE_VERSION
700 // Parallel STL algorithms
701 # if _PSTL_EXECUTION_POLICIES_DEFINED
702 // If <execution> has already been included, pull in implementations
703 # include <pstl/glue_numeric_impl.h>
705 // Otherwise just pull in forward declarations
706 # include <pstl/glue_numeric_defs.h>
707 # define _PSTL_NUMERIC_FORWARD_DECLARED 1
710 // Feature test macro for parallel algorithms
711 # define __cpp_lib_parallel_algorithm 201603L
714 #endif /* _GLIBCXX_NUMERIC */