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
Sovengarde
671 gold badge2 silver badges7 bronze badges
1 Answer 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
MSeifert
154k41 gold badges356 silver badges378 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
wim
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.MSeifert
@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.lang-py
Lyou want to overwrite? Second row? What is the desired output?