Best way to calculate the difference between numpy unsigned ints in Python

I am calculating the absolute difference between two numpy.uint8 in python with d = abs(a - b) , which leads to an overflow error if b greater than a . What is the best way to avoid this?

+4
source share
3 answers

As your comment indicates, this is not int s; they are numpy.uint8 s. Just convert them to int s:

 >>> a, b = map(numpy.uint8, (50, 60)) >>> a - b __main__:1: RuntimeWarning: overflow encountered in ubyte_scalars 246 >>> a, b = map(int, (a, b)) >>> a - b -10 

Since you're worried about speed, here are a couple of tests (borrowing Sven with thanks):

 >>> %timeit abs(int(a) - int(b)) 1000000 loops, best of 3: 410 ns per loop >>> %timeit a - b if a > b else b - a 1000000 loops, best of 3: 470 ns per loop 

So yes, itโ€™s faster, but if we are not talking about doing it hundreds of millions of times, it doesnโ€™t matter.

+3
source

The easiest way is to manually convert your numbers to Python first:

 d = abs(int(a) - int(b)) 

Python ints cannot overflow (unless memory is full).

+2
source

For me, this does not cause an overflow error, it simply leads to false values โ€‹โ€‹if b greater than a . To stay within uint8 borders, use this function:

 def abs_dev (a, b) : sub1 = a - b sub2 = b - a mask = a < b sub1[mask] = sub2[mask] return sub1 
0
source

Source: https://habr.com/ru/post/1436489/


All Articles