According to Numpy.result_type, numpy.float32 can not hold int32 losslessly. When the operation is with an int32, numpy will promotes the resulting value as a float64. Also according to @Eric, the actual int type may change in different environment, so a pre-test is a good practice to avoid some potential surprise.
A previous similar question is suggested for further reading:Numpy casting float32 to float64
. Numpy has a different treatment for purely scalar operations and the operations involving an array. In this case, the division operation involves a ndarray, so when num
is smaller than 65536 but larger thant 255, numpy converts it as int16. Numpy determines int16 can be cast to float32 losslessly while int32 can't. This is shown by np.can_cast(np.int16, np.float32)
gives True
but np.can_cast(np.int32, np.float32)
gives False
.
Thanks for the insightful comments under the question. This answer is a short summary of these comments.