Skip to content

fix: drop NaN again in median for float types - #45

Merged
yoshoku merged 1 commit into
yoshoku:mainfrom
wtn:median
Nov 29, 2026
Merged

yoshoku merged 1 commit into
yoshoku:mainfrom
wtn:median

Conversation

@wtn

@wtn wtn commented Nov 14, 2026

Copy link
Copy Markdown
Contributor
Numo::DFloat[3, Float::NAN, 1, 2].median # => 2.5 (expected 2.0)
Numo::DFloat[Float::NAN, 5, 1].median    # => 5.0 (expected 3.0)
Numo::DFloat[Float::NAN, 1].median       # => NaN (expected 1.0)

Since 8f16066, median on DFloat and SFloat counts NaN values. The sort moves NaN to the end of the buffer, and the loop that followed it used to shrink n past them. The macro template loops over a local i and leaves n unchanged, so the median is read from a buffer that still includes the NaN values.

n now excludes the trailing NaN values. median(nan: true) runs a second iterator, iter_*_median_prnan, which has the same loop and gets the same fix. Numo::DFloat[1, 2, Float::NAN].median(nan: true) returns 1.5 with this change and 2.0 without it.

@yoshoku

yoshoku commented Nov 22, 2026

Copy link
Copy Markdown
Owner

/opencode review

@github-actions

Copy link
Copy Markdown

The working tree is already checked out at the PR commit (036f441), so I built the extension and verified the behavior directly, and also built upstream ruby-numo/numo-narray for comparison.

Review: fix: drop NaN again in median for float types

Verification performed

  • Built the native extension from this branch and confirmed all cases from the PR body now return the expected values (2.0, 3.0, 1.0, NaN for all-NaN, 1.5 for nan: true).
  • Ran the full test suite: 141 runs, 16384 assertions, 0 failures including the new test_median_ignores_nan.
  • Diffed the macro against upstream numo-narray's ext/numo/narray/gen/tmpl/median.c (master): the template there contains the identical loop (for (; n; n--) { if (!isnan(buf[n-1])) break; }) applied to both _ignan and _prnan iterators. So this PR restores exact upstream parity — the right fix for this project.
  • Built upstream and confirmed it produces byte-identical results for every edge case I probed, including the quirky ones below.

Findings

  1. Pre-existing/inherited quirk — median(nan: true) depends on NaN position (not a regression from this PR, but worth a follow-up):

    DFloat[nan, 1, 2].median(nan: true) # => 1.0
    DFloat[1, nan, 2].median(nan: true) # => NaN
    DFloat[1, 2, nan].median(nan: true) # => 1.5
    

    Root cause: qsort_prnan (cmp_prnan in ext/numo/narray/numo/types/float_macro.h:88) treats NaN as "less than everything" in the comparison function, but cmpgt_prnan and the insertion-sort/presorted paths never move NaNs, so NaNs only reliably end up at the tail by accident of input order. The shrink loop then only drops them when they happen to be trailing. Upstream behaves identically, so this is parity-correct, but if the project ever wants true "propagate NaN" semantics for median, qsort_prnan's NaN placement would need fixing first. I verified this same inconsistency exists in freshly built upstream numo-narray.

  2. n == 0 fallback reads buf[0] on a possibly empty buffer (ext/numo/narray/src/mh/median.h:43): if the reduce window is empty, buf[0] is an out-of-bounds read. This is pre-existing (the branch existed before this PR) and unchanged by it — noting for completeness only. The new way n can reach 0 (all-NaN input) is safe, since buf[0] exists and is NaN.

  3. Loop itself is correct: for (; n; n--) with size_t n cannot underflow (decrement only happens while n > 0), and when the last element is non-NaN it breaks immediately with n unchanged. The result computation then correctly uses the shrunk n.

  4. Minor test nit (test/test_narray.rb:2024): assert_equal([1.5, 4.0, 2.0], m.to_a) mixes Float and Integer literals; it passes (minitest compares with ==), but per-element assert_in_delta would be more robust for float assertions. The assert_in_delta calls elsewhere in the new test are appropriate for SFloat since the values are exactly representable.

Verdict

Approve. The change is a minimal, correct restoration of upstream behavior, the new loop is sound, and it comes with regression tests covering single NaN, multiple NaN, all-NaN, nan: true, and the axis: reduction path for both DFloat and SFloat.

github run

@yoshoku

yoshoku commented Nov 29, 2026

Copy link
Copy Markdown
Owner

@wtn I have updated the workflows, so could you please rebase your branch onto main?

The refactor that moved median into a macro template replaced the loop
that trims trailing NaN from the sorted buffer,

    for (; n; n--) {
      if (!isnan(buf[n - 1])) break;
    }

with a loop over a local index whose result was not used. The element
count kept including the NaN values, so the median was taken from the
wrong position: DFloat[3, NaN, 1, 2].median returned 2.5, and
DFloat[NaN, 1].median returned NaN.

Restore the original loop in both the ignan and prnan iterators.

Co-authored-by: Claude Mythos 5.2 <noreply@anthropic.com>

@yoshoku yoshoku left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your contribution.

@yoshoku
yoshoku merged commit da74e24 into yoshoku:main Nov 29, 2026
12 checks passed
@wtn
wtn deleted the median branch November 29, 2026 23:43
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.

2 participants