Skip to content

BUG: fix numpy.quantile for integer inputs - #30376

Open
DerWeh wants to merge 1 commit into
numpy:mainfrom
DerWeh:bugfix/percentile
Open

DerWeh wants to merge 1 commit into
numpy:mainfrom
DerWeh:bugfix/percentile

Conversation

@DerWeh

@DerWeh DerWeh commented Dec 4, 2025

Copy link
Copy Markdown
Contributor

As mentioned in #29315 (see #29315 (comment)), numpy.quantile currently can overflow for integer inputs in spite of returning a float:

>>> np.quantile(np.array([32767, -1], dtype=np.int16), 0.5)
np.float64(49151.0)

This can be fixed by casting integers to floats, before interpolating.
This yields the correct result:

>>> np.quantile(np.array([32767, -1], dtype=np.int16), 0.5)
np.float64(16383.0)

We ensure a consistent behavior by adding a property test:

quantile = np.quantile(a, q)
assert np.min(a) <= quantile
assert quantile <= np.max(a)

So far, this is just a quick fix, I haven't check if all paths are correct.

We probably need to parameterize by the additional parameters of np.quantile.
I just wanted to first cross-check if this is the right approach to fix the issue.

At this point, we still incorrectly get:

>>> np.quantile([1], 0)
np.int64(1)

While the documentation ensures us that we should get np.float64(0.0).
Currently, the return type depends on the value of q:

>>> np.quantile([1], 0.5)
np.float64(1.0)

which is undesired behavior.
I can add the return type to the property test.
We also haven't looked into the second part of the documentation: "If the input contains ... floats smaller than float64, the output data-type is float64."


Another point worth discussing is using np.int64 with values bigger than can be exactly represented by np.float64 (i.e. integers larger than 2⁵³).
I am not quite sure, if we might lose accuracy in this case.
On the other hand, it is clearly documented that we cat np.float64, so we should expect a loss of accuracy for integers outside the representable range.

@DerWeh

DerWeh commented Dec 4, 2025

Copy link
Copy Markdown
Contributor Author

I fail the test

    def test_quantile_gh_29003_Fraction(self):
        r = np.quantile([1, 2], q=Fraction(1))
        assert r == Fraction(2)
        assert isinstance(r, Fraction)

        r = np.quantile([1, 2], q=Fraction(.5))
        assert r == Fraction(3, 2)
        assert isinstance(r, Fraction)

Introduced in #29105.
@eendebakpt says:

There are also some corner cases. For example input (of either the array or the quantile) of type Fraction. Possible output types could be either Fraction or float64.

This is undocumented behavior, and I am not quite sure in which case you would want that...

Documentation only says:

If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.

So my claim is, that if you for whatever reason want Fraction as output, you should either explicitly give out or convert [1, 2] to an array of Fractions.
To my understanding, the test contradicts the documentation.

@MaanasArora MaanasArora left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Seems to patch much of the issue! Agreed that the docs are a bit inconsistent for floats still, so let's wait for maintainer review.

Not sure about the fraction edge case, not familiar with this code. But who knows if this will fail with other object dtypes - perhaps one could special-case for q or even gamma.

q=st.floats(min_value=0, max_value=1),
)
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
def test_quantile_properties(a, q):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should this not be under the TestQuantile class? Also, perhaps a more descriptive name would be better (maybe test_quantile_within_bounds)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Should this not be under the TestQuantile class?

I don't know, but I can put it there. The function doesn't depend on any attributes and I see no application for inheritance, so I thought a free/plain function is more idiomatic than a method.

Also, perhaps a more descriptive name would be better (maybe test_quantile_within_bounds)?

If it stays like this, I agree. I planned on adding the type checks here (and any other property we agree on) and extending the test to cover all methods.

Alternatively, we could write multiple short functions, but it seemed more efficient to me, to scan all inputs only once.

method_props, gtype)
result_shape = virtual_indexes.shape + (1,) * (arr.ndim - 1)
gamma = gamma.reshape(result_shape)
if arr.dtype.kind in ("i", "u"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can this be merged into the if statement above?

if arr.dtype.kind in "iu":
gtype = None

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, you are probably right. But first, we (or I) need to cover all branches. As pointed out above, in the current draft version, the return type still depends on the quantile q.

I hoped to get feedback from the maintainer if I'm on the right track, before putting in all the effort. As soon as we have the correct tests in place, we should indeed try to simplify the code. Thanks for the input.

@seberg seberg Dec 19, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

FWIW, I think this should be moved into _lerp if anything. (this brings up my long term thought that a lerp ufunc would maybe the cleanest thing to solve all of these issues.)
If you have it there, you can also make it quicker than just doing a full cast here I think (at least for very large arrays). Although it may be nice to at least not do this when the input is clearly OK.

EDIT: If you are actually interested in that, at least I think that adding a lerp ufunc would be worthwhile.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants