Skip to content

BUG: fix ma.median dtype promotion for float16/float32 inputs#31560

Open
Atharva2012 wants to merge 1 commit into
numpy:mainfrom
Atharva2012:fix-ma-median-dtype-promotion
Open

BUG: fix ma.median dtype promotion for float16/float32 inputs#31560
Atharva2012 wants to merge 1 commit into
numpy:mainfrom
Atharva2012:fix-ma-median-dtype-promotion

Conversation

@Atharva2012

@Atharva2012 Atharva2012 commented Jun 4, 2026

Copy link
Copy Markdown

PR summary
np.ma.median does not promote float16 and float32 inputs to float64 as documented. The docstring states the return type should be float64 for floats smaller than float64, but the result stays in the input dtype instead.
The bug is in _median in numpy/ma/extras.py. Two code paths, the 1D path and the N-D path, use np.true_divide without first casting to the correct output dtype. The fix computes out_dtype = np.result_type(asorted.dtype, np.float64) and casts before dividing in both paths.

UPDATE: After reviewer feedback, it was found that both np.median and np.ma.median return the same dtype as the input consistently. The issue is in the docstring, not the code. This PR now corrects the docstring in numpy/ma/extras.py to accurately reflect the actual behavior.

Closes #31486 Related to: #29003

First time committer introduction
I am Atharva, I use NumPy for academic projects, but it's my first time contributing to this open source project. I kept the change small and focused on a single well-defined bug.

** AI Disclosure**
AI was used to reword the PR description in more suitable language.

@Atharva2012

Copy link
Copy Markdown
Author

@seberg This is my first PR for this project. Could use your opinion.

@seberg

seberg commented Jun 8, 2026

Copy link
Copy Markdown
Member

Sorry, but this is the wrong approach. You should make sure that ma.median mirrors normal median and if you check that you'll see that if anything this seems like a documentation issue.
(Although the code could call mean() for clarity, although it doesn't matter, the NumPy code does so mainly for some astropy compat stuff that I doubt is super important here.)

@Atharva2012 Atharva2012 force-pushed the fix-ma-median-dtype-promotion branch from 8c4d18f to ec80318 Compare June 8, 2026 20:45
@Atharva2012

Copy link
Copy Markdown
Author

@seberg Thank you for the feedback! After checking, both np.median and np.ma.median return the same dtype as the input consistently, so this is a documentation issue. I've updated the docstring to accurately reflect the actual behavior.

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.

BUG/DOC: numpy.ma.median return dtype does not match documented behavior

2 participants