Skip to content

fix: use averaged ranks for ties in Spearman, guard n<2 - #14889

Merged
cclauss merged 1 commit into
TheAlgorithms:masterfrom
SAnnasJawed:fix/spearman-tied-ranks-and-zero-division
Sep 10, 2026
Merged

cclauss merged 1 commit into
TheAlgorithms:masterfrom
SAnnasJawed:fix/spearman-tied-ranks-and-zero-division

Conversation

@SAnnasJawed

Copy link
Copy Markdown
Contributor

Fixes #14887

Changes made:

  • Fixed assign_ranks() to use averaged ranks for tied values instead of sequential ranks (e.g. [1, 2, 2, 4] now correctly gives [1.0, 2.5, 2.5, 4.0] instead of [1.0, 2.0, 3.0, 4.0]).
  • Added ValueError guard for n<1 to prevent ZeroDivisionError if a single data point is passed.
  • Updated existing doctest for [5, 1, 2, 9, 5] from 0.6 to 0.4, the old value was itself incorrect, produced by the broken sequential ranking.
  • Updated return type annotation on assign_ranks() from list[int] to list[float] since averaged ranks like (2.5) are floats.
  • Added new doctests covering tied values and the n=1 edge case.

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.

@algorithms-keeper algorithms-keeper Bot added enhancement This PR modified some existing files awaiting reviews This PR is ready to be reviewed labels Jul 2, 2026
@algorithms-keeper algorithms-keeper Bot removed the awaiting reviews This PR is ready to be reviewed label Sep 10, 2026
@cclauss
cclauss merged commit b7f4f02 into TheAlgorithms:master Sep 10, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Spearman correlation incorrect for tied values, ZeroDivisionError on n=1

2 participants