A loyalty system stores points as pts = np.array([1201, 350, 85], dtype=np.int64). For a 1.5× points campaign, a notebook runs boosted = pts * 1.5 and then pts *= 1.5. What happens in current NumPy?
Show the answer and explanation
Correct answer: D, pts * 1.5 returns a new float64 array, but pts *= 1.5 raises a casting error: an in-place result must fit the int64 buffer, and float64 → int64 breaks 'same_kind'.
Explanation NumPy
A binary operation allocates a new output, so NumPy's type promotion can choose a wider dtype: int64 × float gives float64, and boosted is [1801.5, 525.0, 127.5].
An in-place operation writes into the existing buffer, so it cannot change the array's dtype. pts *= 1.5 is np.multiply(pts, 1.5, out=pts): the float64 result would have to be cast back to int64, and in-place ufuncs use the 'same_kind' casting rule, which forbids float → int. NumPy raises a UFuncTypeError (a subclass of TypeError): Cannot cast ufunc 'multiply' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'. pts is left unchanged.
| Statement | Result |
|---|---|
pts * 1.5 | new float64 array |
pts *= 2 | fine, the int result fits int64 |
pts *= 1.5 | UFuncTypeError |
pts = pts * 1.5 | rebinds the name to a new float64 array |
np.multiply(pts, 1.5, out=pts, casting="unsafe") | truncates to [1801 525 127] |
For points or money, make the rounding rule explicit, e.g. pts = np.floor(pts * 1.5).astype(np.int64), or np.round if the business rule says so.
Why the distractors fail: NumPy releases before 1.10 did allow this unsafe cast, which is exactly why the rule was tightened; an in-place operation never changes an array's dtype or swaps its buffer; and mixing an int array with a Python float is ordinary type promotion, not an error.
Interview tip: distinguish x = x + y (a new object, the dtype may change) from x += y (the same object and dtype, and the change is visible through every other reference or view of that array).