When doing something with a variable with type numpy.int32, the type changes to numpy.int64, which is why I get unexpected values ​​of variables.

For example, with bitwise operations, the result is not the number I need.

>>> import numpy as np >>> (np.int32(335544318)<<6)>>4 1342177272 >>> type((np.int32(335544318)<<6)>>4) <class 'numpy.int64'> 

If I do not use numpy.int32, I still get 1342177272:

 >>> (335544318<<6)>>4 1342177272 

If you do the same in JavaScript, you get -8, which I just needed:

 > (335544318<<6)>>4 < -8 

To get the same in Python, you must manually change the type back to np.int32 after each action:

 >>> np.int32(np.int32(335544318)<<6)>>4 -8 

I can not understand why this is happening. How can I block the type of a variable so that it retains its 32 bits?

  • What is your numpy version? - MaxU
  • Version numpy 1.11.2, Python 3.5.2 - Alexander Loev
  • in version 1.11.1 (np.int32(335544318)<<6)>>4 gives -8 - MaxU
  • try this: np.right_shift(np.left_shift(np.int32(335544318), 6), 4) - MaxU
  • I installed 1.11.1, and for some reason both options still lead to 1342177272 - Alexander Loev

1 answer 1

NumPy uses implicit type casting , much like it does in C / C ++:

 >>> np.result_type(np.int32(0), 0) dtype('int64') # np.int_ >>> np.result_type(np.int32(0), 1<<62) dtype('int64') >>> np.result_type(np.int32(0), 1<<63) dtype('float64') >>> np.result_type(np.int32(0), 1<<64) dtype('O') # Python object 

To find out the scalar numpy type corresponding to a given Python type, you can use the numpy.obj2sctype() function . For Python int , the numpy.int_ type is used:

 >>> np.obj2sctype(int) == np.int_ True 

When the expression has two scalar types, the result is the smallest type into which they can be converted safely :

 >>> np.promote_types(np.int32, np.int_) == np.int_ True 

np.int_ is usually either np.int32 or np.int64 depending on the system (C long):