0

I have this array:

L = np.array([[5,4],[3,2]])

And I want to change the second bracket.

If I do:

print(L[1] + (-0.6)*L[0])

it will give me this array:

[0,-0.4]

But, if I change it like this:

L[1] = L[1] + (-0.6)*L[0]
print(L)

it prints:

# [[5 4] [0 0]]

Why are the outputs different?

MSeifert
154k41 gold badges356 silver badges378 bronze badges
asked Apr 17, 2017 at 15:55
1
  • What part of L you want to overwrite? Second row? What is the desired output? Commented Apr 17, 2017 at 15:59

1 Answer 1

1

The first example:

L[1] + (-0.6)*L[0]

returns the result of the specified operation, but it isn't assigned so you just have the result.

In your second example

L[1] = L[1] + (-0.6)*L[0]

the result is written to L[1], however the result is cast to the dtype of L. Which is an integer. So the intermediate result is simply truncated.

This "truncation" is the reason why the result isn't "correct":

>>> (L[1] + (-0.6)*L[0]).astype(int) # simulating the truncation
array([0, 0])
answered Apr 17, 2017 at 16:01
Sign up to request clarification or add additional context in comments.

3 Comments

It is interesting that the augmented assignment statement L[1] += -0.6*L[0] will fail because of a casting rule, in this case, but a regular assignment will not fail.
@wim Maybe they just forgot to add it to = as well or they just feel like that's explicit "casting" and therefore allowed while [*]= is implicit and therefore not allowed. Or it's because = doesn't use the ufunc-machinery (which allows to specifiy casting=) and therefore was simply "left" as is. But that's just guessing, maybe worth to ask about it on numpys issue tracker.
It's actually documented behaviour. See the warning mentioned here. Nonetheless, I find the discrepancy surprising (and questionable design choice).

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.