Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting 3D numpy arrays in Python Vs Matlab

I have two 3D numpy arrays and I would like to find out the difference between them.

>>>A.dtype
dtype('uint32')
>>>B.dtype
dtype('uint32')
>>>A.shape
(86, 50, 108)
>>>B.shape
(86, 50, 108)    
>>>A.min()
0
>>>B.min()
0
>>>A.max()
89478487
>>>B.max()
89115767

Now, if we do A - B

>>> diff = abs( A-B );
>>> diff.min()
0
>>> diff.max()
4294967292

Considering the min and max values of both matrices we cannot have 4294967292 as maximum value of the difference matrix. I have also done similar operations in Matlab and the difference diff and maximum value diff.max() are consistent. What is exactly A-B operation doing? My understanding is that the default behaviour for add, subtract, multiply and divide arrays with each other was element-wise operations however there is something funny happening here.

like image 851
Manolete Avatar asked Mar 20 '23 03:03

Manolete


1 Answers

You are using Unsigned 32 bit ints. So you're getting an overflow

>>> numpy.uint32(0) - numpy.uint32(1)
4294967295

Try changing your array's to type int…

>>> A = numpy.array([0,1,2],'uint32')
>>> B = numpy.array([1,2,3],'uint32')
>>> A-B
array([4294967295, 4294967295, 4294967295], dtype=uint32)
>>> A = A.astype(int)
>>> B = B.astype(int)
>>> A-B
array([-1, -1, -1])
like image 180
Charles Avatar answered Apr 01 '23 03:04

Charles