Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions include/xtensor/core/xmath.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1825,12 +1825,21 @@ namespace xt

namespace detail
{
template <class T, class S, class ST>
inline auto mean_division(S&& s, ST e_size)
template <class T, class S, class ST, class D>
inline auto mean_division(S&& s, ST size, const D& ddof)
{
using value_type = typename std::conditional_t<std::is_same<T, void>::value, double, T>;
// Avoids floating point exception when s.size is 0
value_type div = s.size() != ST(0) ? static_cast<value_type>(e_size / s.size()) : value_type(0);
// Avoids floating point exception when s.size is 0. The ddof correction
// applies to the number of samples per output element, not to the total
// size before it is split into output elements.
value_type div = value_type(0);
if (s.size() != ST(0))
{
const ST sample_count = size / s.size();
const ST correction = static_cast<ST>(ddof);
div = sample_count > correction ? static_cast<value_type>(sample_count - correction)
: value_type(0);
}
return std::move(s) / std::move(div);
}

Expand All @@ -1849,7 +1858,7 @@ namespace xt
const size_type size = e.size();
XTENSOR_ASSERT(static_cast<size_type>(ddof) <= size);
auto s = sum<T>(std::forward<E>(e), std::forward<X>(axes), es);
return mean_division<T>(std::move(s), size - static_cast<size_type>(ddof));
return mean_division<T>(std::move(s), size, ddof);
}

template <class T, class E, class I, std::size_t N, class D, class EVS>
Expand All @@ -1859,7 +1868,7 @@ namespace xt
const size_type size = e.size();
XTENSOR_ASSERT(static_cast<size_type>(ddof) <= size);
auto s = sum<T>(std::forward<E>(e), axes, es);
return mean_division<T>(std::move(s), size - static_cast<size_type>(ddof));
return mean_division<T>(std::move(s), size, ddof);
}

template <class T, class E, class D, class EVS, XTL_REQUIRES(is_reducer_options<EVS>, xtl::is_integral<D>)>
Expand Down
16 changes: 16 additions & 0 deletions test/test_extended_xmath_reducers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2832,4 +2832,20 @@ namespace xt
EXPECT_TRUE(xt::allclose(vr_ddof_with_axes_arr, py_vr_ddof));
}

TEST(xtest_extended_xmath, variance_axis_ddof)
{
// ddof is applied per output element, not to the total size before
// it is split into output elements (github issue #2937).
xarray<double> a = {{1., 3., 5.}, {2., 4., 6.}};

auto v = xt::variance(a, {1}, 2);
EXPECT_EQ(v(0), 8.);
EXPECT_EQ(v(1), 8.);

std::vector<std::size_t> axes = {1};
auto v_axes = xt::variance(a, axes, 2);
EXPECT_EQ(v_axes(0), 8.);
EXPECT_EQ(v_axes(1), 8.);
}

}
Loading