Skip to content

np.conj has divergent behavior from ndarray.conj #17124

Open

Description

@mruberry

np.conj returns a new array, but ndarray.conj returns self for non-complex arrays and a new array for complex arrays. Example:

a = np.array((1, 2, 3), dtype=np.int64)

# np.conj returns a copy of a
fn_result = np.conj(a)
fn_result[0] = 0
a
: array([1, 2, 3])

# ndarray.conj returns a itself
method_result = a.conj()
method_result[0] = 0
a
: array([0, 2, 3])

# ndarray.conj returns a copy for complex arrays
a = np.array((1, 2, 3), dtype=np.complex64)
complex_method_result = a.conj()
complex_method_result[0] = 100
a
: array([1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64)

The divergence between function and method and different dtypes seems very odd.

Activity

  1. charris commented on Aug 20, 2020

    @charris
    Member

    seems very odd

    Standard behavior, functions usually make copies, methods don't if they don't need to. We should probably do a better job of documenting the view vs copy behavior of all our methods. The sort method is a bit of an outlier as it sorts in place like Python does, and while conj could also change the imaginary part in place, it would break up a bunch of code to change that now.

  2. mruberry commented on Aug 20, 2020

    @mruberry
    Author

    As some follow-up context, other NumPy functions are also inconsistent here. np.round and np.trunc, for example, will return self when called on an int64 array.

  3. rgommers commented on Aug 20, 2020

    @rgommers
    Member

    Yes, the inconsistency is quite annoying, but it's also hard to fix up because of the danger of silently introducing bugs in end user code.

    I suspect the best we can do is document it well.

    Standard behavior, functions usually make copies, methods don't if they don't need t

    I don't think that has been the design principle. The goal was, I think, returning views whenever possible, and copies if needed (remember, e.g., the np.diag stuff where we tried deprecating and then changing to a view to comply to this principle).

    I agree that the expectation that function and method work the same is sensible - it would be mine as well.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions