Skip to content

BUG: make round consistently return a copy #29137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
BUG: make round consistently return a copy
Otherwise, `round` returns a view for integer arguments and a copy otherwise.
All other "rounding" functions (ceil, floor, trunc, rint), always return copies.
Thus, make `round` consistent with them.
  • Loading branch information
ev-br committed Jun 7, 2025
commit ead856347a0b0952e82ae537c02721663742f25f
3 changes: 1 addition & 2 deletions numpy/_core/src/multiarray/calculation.c
Original file line number Diff line number Diff line change
Expand Up @@ -637,8 +637,7 @@ PyArray_Round(PyArrayObject *a, int decimals, PyArrayObject *out)
return (PyObject *)out;
}
else {
Py_INCREF(a);
return (PyObject *)a;
return PyArray_Copy(a);
}
}
if (decimals == 0) {
Expand Down
10 changes: 10 additions & 0 deletions numpy/_core/tests/test_multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -2075,6 +2075,7 @@ def check_round(arr, expected, *round_args):
assert_equal(out, expected)
assert out is res

check_round(np.array([1, 2, 3]), [1, 2, 3])
check_round(np.array([1.2, 1.5]), [1, 2])
check_round(np.array(1.5), 2)
check_round(np.array([12.2, 15.5]), [10, 20], -1)
Expand All @@ -2083,6 +2084,15 @@ def check_round(arr, expected, *round_args):
check_round(np.array([4.5 + 1.5j]), [4 + 2j])
check_round(np.array([12.5 + 15.5j]), [10 + 20j], -1)

@pytest.mark.parametrize('dt', ['uint8', int, float, complex])
def test_round_copies(self, dt):
a = np.arange(3, dtype=dt)
assert not np.shares_memory(a.round(), a)
assert not np.shares_memory(a.round(decimals=2), a)

out = np.empty(3, dtype=dt)
assert not np.shares_memory(a.round(out=out), a)

def test_squeeze(self):
a = np.array([[[1], [2], [3]]])
assert_equal(a.squeeze(), [1, 2, 3])
Expand Down
Loading