Skip to content

Fix ddof correction in variance over axes - #2938

Open
vera-rubin wants to merge 1 commit into
xtensor-stack:masterfrom
vera-rubin:fix/variance-axis-ddof
Open

vera-rubin wants to merge 1 commit into
xtensor-stack:masterfrom
vera-rubin:fix/variance-axis-ddof

Conversation

@vera-rubin

Copy link
Copy Markdown

Checklist

  • The title and commit message(s) are descriptive.
  • Small commits made to fix your PR have been squashed to avoid history pollution.
  • Tests have been added for new features or bug fixes.
  • API of new functions and classes are documented.

Description

xt::variance(e, axes, ddof) subtracted ddof from the total element count before dividing by the number of output lanes, so the divisor was (size - ddof) / out_size rather than size / out_size - ddof. For a 2x3 array reduced over axis 1 with ddof=2, this returned {4, 4} instead of {8, 8}.

detail::mean_division now takes ddof separately and subtracts it from the per-lane count. mean passes ddof = 0, so its results are unchanged. The existing assertion still checks ddof against the total size. Behavior for ddof >= N remains unresolved, where N is the sample count per lane. For ddof > N, the per-lane subtraction can underflow the unsigned divisor.

Tested on Linux x86_64 in C++20 mode against d9a57b696f42a815a40f08db5cb206d8960a9f4b, with xtl 0.8.0 at ef84e9f27020ad54961c99acd293d80d4b775dd3.

We added xmath.variance_ddof to test_xmath.cpp. It fails before the change and passes after. The full test_xtensor_lib suite passes with GCC 13.3, and the reproducer from the issue now matches NumPy with GCC 13.3 and Clang 18.1.

Fixes #2937

— ChipLab · CLAB-2026-880

The divisor for an axis reduction was computed as
(total_size - ddof) / output_size, so ddof was subtracted from the
total element count before dividing by the number of output lanes.
Divide first to get the per-lane sample count, then subtract ddof.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Axis variance applies ddof before computing the per-lane sample count

1 participant