Skip to content

Commit 11a4425

Browse files
authored
Merge pull request #2278 from JohanMabille/doc
Updated reducer docs according to recent changes
2 parents dba06f8 + 6de0748 commit 11a4425

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

docs/source/operator.rst

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,39 @@ the evaluation and get the result:
218218
xt::xarray<double> arr = some_init_function({3, 2, 4, 6, 5});
219219
double res = xt::reduce([](double a, double b) { return a*a + b*b; }, arr)();
220220
221+
The ``value_type`` of a reducer is the traditional result type of the reducing operation. For instance,
222+
the ``value_type`` of the reducer for the sum is:
223+
224+
- ``int`` if the underlying expression holds ``int`` values
225+
- ``int`` if the underlying expression holds ``short`` values, because ``short + short`` = ``int``
226+
227+
You can pass a template argument to the reducer functions to specify the type of the initial value of
228+
the reduction. This allows you to "promote" the value type of the reducer and limit overflows in
229+
computation:
230+
231+
.. code::
232+
233+
#include "xtensor/xarray.hpp"
234+
#include "xtensor/xreducer.hpp"
235+
236+
xt::xarray<int> arr = some_init_function({3, 2, 4, 6, 5});
237+
auto s1 = xt::sum<short>(arr); // No effect, short + int = int
238+
auto s2 = xt::sum<long int>(arr); // The value_type of s2 is long int
239+
240+
When you write generic code and you want to limit overflows, you can use ``xt::big_promote_value_type_t``
241+
as shown below:
242+
243+
.. code::
244+
245+
#include "xtensor/xarray.hpp"
246+
#include "xtensor/xreducer.hpp"
247+
248+
template <class E>
249+
void my_computation(E&& e)
250+
{
251+
auto s = xt::sum<xt::big_promote_value_type_t<E>>(e);
252+
}
253+
221254
Accumulators
222255
------------
223256

docs/source/quickref/reducer.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,15 @@ Sum
3030
// Outputs {6, 15}, but r3 is an unevaluated expression
3131
// the values are computed upon each access
3232
33+
auto r4 = xt::sum<long int>(a, {1});
34+
// r4 holds long int values
35+
36+
auto r5 = xt::sum<short>(a, {1});
37+
// r5 hols int values
38+
39+
auto r6 = xt::sum<xt::big_promote_value_type<decltype(a)>>(a, {1});
40+
// r6 holds long long int values
41+
3342
Prod
3443
----
3544

@@ -40,6 +49,8 @@ Prod
4049
xt::xarray<int> r1 = xt::prod(a);
4150
int r2 = xt::prod(a)();
4251
auto r3 = xt::prod(a, {0});
52+
auro r4 = xt::prod<long int>(a, {0});
53+
auto r5 = xt::prod<xt::big_promote_value_type<decltype(a)>>(a, {1});
4354
4455
Mean
4556
----

0 commit comments

Comments
 (0)