Skip to content

ENH: Implement __round__ special method for ndarrays #6248

Open

Description

@anntzer

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).

Activity

  1. shoyer commented on Aug 26, 2015

    @shoyer
    Member

    np.round already calls the round method if available. I think this is exactly what you're looking for?

  2. anntzer commented on Aug 26, 2015

    @anntzer
    ContributorAuthor

    no?

    In [1]: round(np.array([1]))
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-1-ab6f39befe0c> in <module>()
    ----> 1 round(np.array([1]))
    
    TypeError: type numpy.ndarray doesn't define __round__ method
    
  3. shoyer commented on Aug 26, 2015

    @shoyer
    Member

    Ah. I misread your initial post.

    On Python 3, this does actually work:

    In [24]: round(np.array([1]))
    Out[24]: 1.0
    

    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.
    
  4. anntzer commented on Aug 26, 2015

    @anntzer
    ContributorAuthor

    But just like __abs__, __round__ (which is implemented for scalar dtypes) can return an object of any type:

    In [1]: class C:
       ...:     def __round__(self): return "foo"
       ...: 
    
    In [2]: round(C())
    Out[2]: 'foo'
    
  5. shoyer commented on Aug 26, 2015

    @shoyer
    Member

    You're right, this should be totally doable:

     class C:
        def __round__(self, decimals=0):
            return round(np.pi, decimals) * np.ones(3)
    In [7]: round(C())
    Out[7]: array([ 3.,  3.,  3.])
    
    In [8]: round(C(), 2)
    Out[8]: array([ 3.14,  3.14,  3.14])
    
    In [9]: round(C(), 1)
    Out[9]: array([ 3.1,  3.1,  3.1])
    
  6. seberg commented on Aug 27, 2015

    @seberg
    Member

    @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.

  7. anntzer commented on Feb 16, 2016

    @anntzer
    ContributorAuthor

    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.

  8. seberg commented on Feb 16, 2016

    @seberg
    Member

    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.

  9. anntzer commented on May 11, 2016

    @anntzer
    ContributorAuthor

    The return type issue is at #5700, so let's keep this issue just about rounding entire arrays with the builtin round.

  10. eric-wieser commented on Sep 29, 2017

    @eric-wieser
    Member

    On Python 3, this does actually work

    Doesn't work for me in 1.13. Was this removed?

    since python 3 says that the result should be integer for decimals=0

    Not quite:

    >>> round(123.45, 0)
    123.00
    >>> round(123.45, None)
    123
  11. eric-wieser commented on Sep 29, 2017

    @eric-wieser
    Member

    If we implement round(np.ndarray), it needs to fall back on calling the builtin __round__ on the scalars for object arrays (#9791)

  12. maxnoe commented on May 14, 2020

    @maxnoe

    Any progress on this? Just ran into this again. Is there a blocking issue here?

  13. seberg commented on May 14, 2020

    @seberg
    Member

    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.

  14. asmeurer commented on Nov 16, 2022

    @asmeurer
    Member

    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

    class ndarray:
        def __round__(self, ndigits=None):
            if self.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:
                if ndigits is None:
                    raise ValueError('round on ndarray with ndigits=None is not supported')
                return np.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.

  15. added
    triage review
    on Nov 17, 2022
  16. changed the title [-]Implement __round__ specialmethod for ndarrays?[/-] [+]ENH: Implement __round__ special method for ndarrays[/+] on Nov 17, 2022
  17. miccoli commented on Dec 1, 2022

    @miccoli
    Contributor

    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:

    >>> round(a)
    1e+300
    >>> round(round(a))
    1000000000000000052504760255204420248704468581108159154915854115511802457988908195786371375080447864043704443832883878176942523235360430575644792184786706982848387200926575803737830233794788090059368953234970799945081119038967640880074652742780142494579258788820056842838115669472196386865459400540160
    

    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)

  18. added
    triaged
    and removed
    triage review
    on Dec 13, 2022
  19. mhvk commented on Dec 13, 2022

    @mhvk
    Contributor

    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.

  20. seberg commented on Dec 14, 2022

    @seberg
    Member

    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.

    It could still be allowed in some future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    01 - Enhancementcomponent: numpy._coretriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions