Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm getting a TypeError for a += b, but not b += a (numpy)

why I'm getting TypeError for a += b but it works fine for b += a for below code

import numpy as np
a = np.ones((2,3), dtype=int) 
b = np.random.random((2,3))
a += b
like image 329
Vinay Sharma Avatar asked Dec 08 '22 13:12

Vinay Sharma


2 Answers

Report the whole TypeError!

----> 3 a += b

TypeError: Cannot cast ufunc add output from dtype('float64') to 
   dtype('int64') with casting rule 'same_kind'

a is integer dtype, right? b is float. Add a float and integer and the result is a float. But a+=... is expected to put that float into a, the integer array. numpy does not want to do that.

But this is fine:

In [3]: a = a + b
In [4]: a
Out[4]: 
array([[1.01407496, 1.96122364, 1.91447533],
       [1.68130058, 1.99773138, 1.50043386]])

The original integer array, a has now been replaced by a float array. That's a Python level assignment, where as a+=... attempts to modify the original a array (in-place). The distinction is important.

like image 100
hpaulj Avatar answered Dec 21 '22 04:12

hpaulj


The error message will give you a hint:

TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int32') with casting rule 'same_kind'

a is an array of int32s and b is an array of float64s. Adding an int32 and a float64 (nevermind which comes first), will produce a float64. This value cannot be stored in a, but can be stored in b.

If you define a to use dtype=float, a+=b would be perfectly legal:

a = np.ones((2,3), dtype=float)
like image 38
Mureinik Avatar answered Dec 21 '22 04:12

Mureinik