0

can add int to float but can't add float to int

import numpy as np a = np.full((2,3),3, dtype=int) print(a) print(a.dtype.name) #int32 b = np.random.random((2,3)) print(b) #float64 print(b.dtype.name) b += a #this works print(b) a += b #this doesnt work print(a) #error message TypeError Traceback (most recent call last) <ipython-input-44-ab0d7ebed8b7> in <module> 10 print(b) 11 ---> 12 a += b 13 print(a) 14 TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int32') with casting rule 'same_kind' """ I don't understand, I can add int to float but can't do the reverse """

25th Jul 2019, 11:36 AM
Joseph Ojo
Joseph Ojo - avatar
5 Answers
+ 1
They may look similar, but they are treated differently. "The += operator preserves the type of the array. In other words, an array of integers remains an array of integers. [...] On the other hand, a=a+b creates a brand new array for the sum, and rebinds a to point to this new array". https://stackoverflow.com/a/10740003
25th Jul 2019, 1:34 PM
Diego
Diego - avatar
+ 1
Diego Understood thanks
25th Jul 2019, 3:06 PM
Joseph Ojo
Joseph Ojo - avatar
0
a = a+b
25th Jul 2019, 1:01 PM
Diego
Diego - avatar
0
this is because Python implicitly (behind the scenes) converts the int to a float whenever a float is used in the code. just like / (division) makes an int a float. 9+3=12 but 9/3=3.0 this “secret” conversion doesn’t work the other way around.
25th Jul 2019, 1:01 PM
Brave Tea
Brave Tea - avatar
0
Brave Tea thanks for the insight and Diego a = a+b works. But its confusing coz a += b means the same thing as a = a+b, so why should one work and the other not work. thanks
25th Jul 2019, 1:21 PM
Joseph Ojo
Joseph Ojo - avatar