Skip to content

Commit 49c96ae

Browse files
CAOShurongShurong Cao
andauthored
Fix block_replicate promoting float16/float32/complex64 inputs to float64 (#20364)
* Fix block_replicate promoting float16/float32/complex64 inputs to float64 (fixes #20360) * Rename changelog fragment to match PR number 20364 --------- Co-authored-by: Shurong Cao <[email protected]>
1 parent 3ebe758 commit 49c96ae

3 files changed

Lines changed: 22 additions & 2 deletions

File tree

‎astropy/nddata/blocks.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,8 @@ def block_replicate(data, block_size, conserve_sum=True):
207207
data = np.repeat(data, block_size[i], axis=i)
208208

209209
if conserve_sum:
210-
# in-place division can fail due to dtype casting rule
211-
data = data / np.prod(block_size)
210+
# in-place division can fail due to dtype casting rule;
211+
# cast to Python int to avoid promoting float16/float32/complex64 under NEP 50
212+
data = data / int(np.prod(block_size))
212213

213214
return data

‎astropy/nddata/tests/test_blocks.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,21 @@ def test_block_size_len(self):
171171
data = np.arange(5)
172172
with pytest.raises(ValueError):
173173
block_replicate(data, (2, 2))
174+
175+
@pytest.mark.parametrize(
176+
("in_dtype", "expected_dtype"),
177+
[
178+
(np.float16, np.float16),
179+
(np.float32, np.float32),
180+
(np.float64, np.float64),
181+
(np.complex64, np.complex64),
182+
(np.complex128, np.complex128),
183+
(np.int32, np.float64),
184+
],
185+
)
186+
def test_conserve_sum_dtype(self, in_dtype, expected_dtype):
187+
# Regression test for #20360: conserve_sum=True should preserve float/complex dtypes
188+
data = np.ones((2, 2), dtype=in_dtype)
189+
result = block_replicate(data, 2, conserve_sum=True)
190+
assert result.dtype == expected_dtype
191+
assert block_replicate(data, 2, conserve_sum=False).dtype == in_dtype
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix ``block_replicate`` with ``conserve_sum=True`` inadvertently promoting ``float16``, ``float32``, and ``complex64`` input arrays to wider dtypes.

0 commit comments

Comments
 (0)