Skip to content

Conversation

@rottenstea
Copy link

This commit addresses the following BUG: quantile should error when weights are all zeros #28589

Previously, np.quantile with all weights set to zero returned the first sample. This is fixed now via adding an explicit check that raises a ValueError when all weights are zero, preventing division by zero in the CDF.

  • Added the weight check in _quantile (line 4874 ff) to detect all-zero weights and raise an error.
  • Added a test in test_function_base.py to verify this behavior.
  • Added a second test to ensure existing quantile functionality remains unchanged.

This should close #28589

…eights are all zeros #28589

Previously, np.quantile with all weights set to zero returned the first sample. This is fixed now via adding an explicit check that raises a
ValueError when all weights are zero, preventing division by zero in the CDF.

- Added the weight check in `_quantile` (line 4874 ff) to detect all-zero weights and raise an error.
- Added a test in `test_function_base.py` to verify this behavior.
- Added a second test to ensure existing quantile functionality remains unchanged.

This should close #28589
result = np.quantile(arr, quantile, weights=weights, method='inverted_cdf')
expected = 2.5

assert np.isclose(result, expected)
Copy link
Contributor

Choose a reason for hiding this comment

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

Hopefully this part of the diff isn't really needed--presumably we have sufficient testing that if you broke the numerical behavior of quantile an existing test would fail.

That said, this test actually does fail--maybe there is a problem with the test design?

Copy link
Contributor

Choose a reason for hiding this comment

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

As an aside, assert_allclose() is generally preferable in testing--it tends to give better feedback when something fails, etc.

weights = np.array([0, 0, 0, 0])

with pytest.raises(ValueError, match="All weights are zero, cannot compute quantile."):
np.quantile(arr, quantile, weights=weights, method='inverted_cdf')
Copy link
Contributor

Choose a reason for hiding this comment

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

Note for other NumPy devs--this/this PR is very similar to gh-28597

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

Projects

Status: Pending authors' response

Development

Successfully merging this pull request may close these issues.

BUG: quantile should error when weights are all zeros

2 participants