You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ENH: Implement __round__ special method for ndarrays #6248
This would allow calling round(array). While this would certainly be equivalent to np.round(array), a similar feature is already there with abs(array) (which calls __abs__) and np.abs(array).
But it still doesn't work for arrays of more than 1 element:
In [25]: round(np.array([1, 2]))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-dc44baf3e179> in <module>()
----> 1 round(np.array([1, 2]))
TypeError: only length-1 arrays can be converted to Python scalars
I think the problem here is with Python signature for round:
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
@shoyer I think round is implemented for single element arrays. I frankly hate this (for 0-d would be fine, but I do not like this single element stuff, but so be it).
It is actually incorrect in some sense on python 3, since python 3 says that the result should be integer for decimals=0 (also this works just as well on python 2).
The question is, whether round is in some sense special, or can like abs just operate on the whole array. Right now it is in some it is more like float or int, so that it decides that the result must be scalar:
In [7]: type(round(np.array([1])))
Out[7]: float
It might be OK to consider changing this, since it is generalization, I guess it is unlikely to break much. Ideally I would like an integer return as well for decimals=0, though that seems hard/impossible, since it requires an unsafe casting without arbitrary length integers.
I don't really think unsafe casting is a problem, or at least CPython decided it wasn't a problem:
In [1]: round(1e308)
Out[1]: 100000000000000001097906362944045541740492309677311846336810682903157585404911491537163328978494688899061249669721172515611590283743140088328307009198146046031271664502933027185697489699588559043338384466165001178426897626212945177628091195786707458122783970171784415105291802893207873272974885715430223118336
Especially given that numpy now tries to enforce using ints rather than floats as indices, I think returning integers when applicable should be preferred.
I think my point was that your integer there is not representable in NumPy integer types. For the scalars, we could actually return the int, but for arrays of float, we don't want to return an array of objects probably. So I think the situation is not ideal, though not sure what the solution is.
We did change it for scalars, but not implement for arrays since there is the type issue, that no argument round is special. There is also the issue that round(2e100) actually works in Python, but requires arbitrary precision integers which makes the cast to int more straight forward.
I am not sure those should be show blockers, but that is the reason for it never moving.
I don't think there is ambiguity implementing __round__ when ndigits is not None. NumPy could raise an exception when it is. The implementation would be something like
classndarray:
def__round__(self, ndigits=None):
ifself.dtype==object:
# Apply round(i, ndigits) to each element of self.# This branch is unnecessary if https://github.com/numpy/numpy/issues/9791 is implemented.else:
ifndigitsisNone:
raiseValueError('round on ndarray with ndigits=None is not supported')
returnnp.round(self, ndigits)
This would make round work exactly the same as np.round, with the exception of the missing out argument.
Alternatively, we could just let ndigits=None mean the same thing as ndigits=0. This would break the documented Python behavior, but would let round(x) with no second argument match np.round(x).
Personally I'm -1 to differing behavior on scalars or any sort of value-based behavior.
I think that we must accept the fact that round(x, ndigits=None) cannot be unambiguously defined when x is a numpy array.
In my opinion it is way better to be explicit and error out, than to arbitrary choose one of the possible options. By the way I think that there is noting wrong in leaving __round__ undefined for numpy arrays.
I would also point out that __round__ would work also for 0-d arrays.
Current behaviour is
>>> a = np.array(1e300)
>>> round(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type numpy.ndarray doesn't define __round__ method
>>> np.round(a)
1e+300
>>> round(np.round(a))
1000000000000000052504760255204420248704468581108159154915854115511802457988908195786371375080447864043704443832883878176942523235360430575644792184786706982848387200926575803737830233794788090059368953234970799945081119038967640880074652742780142494579258788820056842838115669472196386865459400540160
This is strange, but undestandable, if you manage to accept that numpy likes to transform 0-d arrays into scalars.
On the contrary, If we make __round__(x, None) equal to np.round(x, decimals=0) then this would become:
which is ugly as sin, since it breaks the round(round(x)) == round(x) invariant.
So I'm +1 for keeping python round and np.round clearly distinct in terms of their semantics and do not equate round(x, ndigits=None) to np.round(x, decimals=0)
Partially, this seems to be a question also of whether the current round(numpy_scalar) is desired behaviour. I also do not like scalars and arrays treated differently.
An alternative would be to generalize and have round(array, ndigits=None) cast to int64 (raising or warning on overflow). That would be backwards compatible except in cases like 1e300 where the current answer is already not great.
Sounds like we should just start with decimals=None raising an informative error, that way users can use round and get an informative error when that doesn't work.
Activity
shoyer commentedon Aug 26, 2015
np.roundalready calls theroundmethod if available. I think this is exactly what you're looking for?anntzer commentedon Aug 26, 2015
no?
shoyer commentedon Aug 26, 2015
Ah. I misread your initial post.
On Python 3, this does actually work:
But it still doesn't work for arrays of more than 1 element:
I think the problem here is with Python signature for
round:anntzer commentedon Aug 26, 2015
But just like
__abs__,__round__(which is implemented for scalar dtypes) can return an object of any type:shoyer commentedon Aug 26, 2015
You're right, this should be totally doable:
seberg commentedon Aug 27, 2015
@shoyer I think round is implemented for single element arrays. I frankly hate this (for 0-d would be fine, but I do not like this single element stuff, but so be it).
It is actually incorrect in some sense on python 3, since python 3 says that the result should be integer for
decimals=0(also this works just as well on python 2).The question is, whether round is in some sense special, or can like abs just operate on the whole array. Right now it is in some it is more like
floatorint, so that it decides that the result must be scalar:It might be OK to consider changing this, since it is generalization, I guess it is unlikely to break much. Ideally I would like an integer return as well for
decimals=0, though that seems hard/impossible, since it requires an unsafe casting without arbitrary length integers.anntzer commentedon Feb 16, 2016
I don't really think unsafe casting is a problem, or at least CPython decided it wasn't a problem:
Especially given that numpy now tries to enforce using ints rather than floats as indices, I think returning integers when applicable should be preferred.
seberg commentedon Feb 16, 2016
I think my point was that your integer there is not representable in NumPy integer types. For the scalars, we could actually return the int, but for arrays of float, we don't want to return an array of objects probably. So I think the situation is not ideal, though not sure what the solution is.
anntzer commentedon May 11, 2016
The return type issue is at #5700, so let's keep this issue just about rounding entire arrays with the builtin round.
eric-wieser commentedon Sep 29, 2017
Doesn't work for me in 1.13. Was this removed?
Not quite:
eric-wieser commentedon Sep 29, 2017
If we implement
round(np.ndarray), it needs to fall back on calling the builtin__round__on the scalars for object arrays (#9791)maxnoe commentedon May 14, 2020
Any progress on this? Just ran into this again. Is there a blocking issue here?
seberg commentedon May 14, 2020
We did change it for scalars, but not implement for arrays since there is the type issue, that no argument round is special. There is also the issue that
round(2e100)actually works in Python, but requires arbitrary precision integers which makes the cast to int more straight forward.I am not sure those should be show blockers, but that is the reason for it never moving.
asmeurer commentedon Nov 16, 2022
I don't think there is ambiguity implementing
__round__whenndigitsis notNone. NumPy could raise an exception when it is. The implementation would be something likeThis would make
roundwork exactly the same asnp.round, with the exception of the missingoutargument.Alternatively, we could just let ndigits=None mean the same thing as ndigits=0. This would break the documented Python behavior, but would let round(x) with no second argument match np.round(x).
Personally I'm -1 to differing behavior on scalars or any sort of value-based behavior.
[-]Implement __round__ specialmethod for ndarrays?[/-][+]ENH: Implement __round__ special method for ndarrays[/+]miccoli commentedon Dec 1, 2022
I think that we must accept the fact that
round(x, ndigits=None)cannot be unambiguously defined whenxis a numpy array.In my opinion it is way better to be explicit and error out, than to arbitrary choose one of the possible options. By the way I think that there is noting wrong in leaving
__round__undefined for numpy arrays.I would also point out that
__round__would work also for 0-d arrays.Current behaviour is
This is strange, but undestandable, if you manage to accept that numpy likes to transform 0-d arrays into scalars.
On the contrary, If we make
__round__(x, None)equal tonp.round(x, decimals=0)then this would become:which is ugly as sin, since it breaks the
round(round(x)) == round(x)invariant.So I'm +1 for keeping python
roundandnp.roundclearly distinct in terms of their semantics and do not equateround(x, ndigits=None)tonp.round(x, decimals=0)mhvk commentedon Dec 13, 2022
Partially, this seems to be a question also of whether the current
round(numpy_scalar)is desired behaviour. I also do not like scalars and arrays treated differently.An alternative would be to generalize and have
round(array, ndigits=None)cast toint64(raising or warning on overflow). That would be backwards compatible except in cases like1e300where the current answer is already not great.seberg commentedon Dec 14, 2022
Sounds like we should just start with
decimals=Noneraising an informative error, that way users can useroundand get an informative error when that doesn't work.It could still be allowed in some future.