5

I have a numpy.float32 matrix V, then I did a division with a integer scalar value:

V = V/num

where num is an integer. The outcome is somewhat surprising that V is converted to a numpy.float64 matrix.

Can anyone help understand why this is so?

Thanks!

13
  • What, exactly is num? Commented Nov 14, 2017 at 21:06
  • 1
    It's probably because casting int to float32 is considered unsafe by numpy (try 'np.can_cast(int, np.float32`) Commented Nov 14, 2017 at 21:07
  • 1
    If I use an int, I still get an array of np.float32. Can you please provide a minimal reproducible example? Commented Nov 14, 2017 at 21:08
  • 1
    @PaulPanzer it depends on the int in question, e.g. np.can_cast(2**15, np.float32) returns True for me, but np.can_cast(2**16, np.float32) returns False Commented Nov 14, 2017 at 21:09
  • 1
    See stackoverflow.com/questions/45949263/… Commented Nov 14, 2017 at 21:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.