Skip to content

The type conversion problem of array operations #11485

Closed

Description

@yydcnjjw
a = np.array([0,255], dtype='uint8')
output:array([  0, 255], dtype=uint8)

a * 2
output:array([  0, 254], dtype=uint8) // become  the top eight after the operation

b = np.array([1, 255], dtype='uint8')
b * 256
output:array([  256, 65280], dtype=uint16) // Automatically become the type of uint16

The change of the variable type depends on the minimum of the array?

Activity

  1. charris commented on Jul 3, 2018

    @charris
    Member

    Hmm, that looks like a bug, and maybe a very old one. The array data type should dominate the scalar unless a float is involved. It may be intended behavior, but I cannot think why.

  2. seberg commented on Jul 3, 2018

    @seberg
    Member

    Its the old problem of "oh a scalar, lets see what the minimum type is when considering the other array", and if the arrays type happens to be good enoug, it uses that... I.e. the 256 scalar is too large for uint8, so it decides that uint16 is necessary, but 2 fits uint8, so that is taken in the first example.

  3. charris commented on Jul 3, 2018

    @charris
    Member

    Arggghhhh, I didn't know that was the policy, that's awful. I thought that within the same kind, the array type was always dominant, which is simple to understand and has the virtue that the output type only depends on the code, not the code and the input values.

  4. seberg commented on Jul 3, 2018

    @seberg
    Member
  5. eric-wieser commented on Jul 10, 2018

    @eric-wieser
    Member

    Relevant is #10322, which here looks like:

    >>> np.result_type(np.int8, 2)
    dtype('int8')
    >>> np.result_type(np.int8, 256)
    dtype('int16')
    
  6. seberg commented on Jan 30, 2024

    @seberg
    Member

    Closing, this is effectively fixed by NEP 50 adoption in main/NumPy 2.0.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions