From c7fb5156a439c0fc62781662ec8a59e96ba995ba Mon Sep 17 00:00:00 2001 From: Tyagiquamar Date: Thu, 19 Nov 2026 14:35:27 +0530 Subject: [PATCH] Fix axis variance divisor when ddof is applied --- include/xtensor/core/xmath.hpp | 21 +++++++++++++++------ test/test_extended_xmath_reducers.cpp | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/include/xtensor/core/xmath.hpp b/include/xtensor/core/xmath.hpp index 401de8a73..f1e34533d 100644 --- a/include/xtensor/core/xmath.hpp +++ b/include/xtensor/core/xmath.hpp @@ -1825,12 +1825,21 @@ namespace xt namespace detail { - template - inline auto mean_division(S&& s, ST e_size) + template + inline auto mean_division(S&& s, ST size, const D& ddof) { using value_type = typename std::conditional_t::value, double, T>; - // Avoids floating point exception when s.size is 0 - value_type div = s.size() != ST(0) ? static_cast(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(ddof); + div = sample_count > correction ? static_cast(sample_count - correction) + : value_type(0); + } return std::move(s) / std::move(div); } @@ -1849,7 +1858,7 @@ namespace xt const size_type size = e.size(); XTENSOR_ASSERT(static_cast(ddof) <= size); auto s = sum(std::forward(e), std::forward(axes), es); - return mean_division(std::move(s), size - static_cast(ddof)); + return mean_division(std::move(s), size, ddof); } template @@ -1859,7 +1868,7 @@ namespace xt const size_type size = e.size(); XTENSOR_ASSERT(static_cast(ddof) <= size); auto s = sum(std::forward(e), axes, es); - return mean_division(std::move(s), size - static_cast(ddof)); + return mean_division(std::move(s), size, ddof); } template , xtl::is_integral)> diff --git a/test/test_extended_xmath_reducers.cpp b/test/test_extended_xmath_reducers.cpp index da093446c..83f9c7959 100644 --- a/test/test_extended_xmath_reducers.cpp +++ b/test/test_extended_xmath_reducers.cpp @@ -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 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 axes = {1}; + auto v_axes = xt::variance(a, axes, 2); + EXPECT_EQ(v_axes(0), 8.); + EXPECT_EQ(v_axes(1), 8.); + } + }