In C is there a branch-less technique to compute the absolute difference between two unsigned ints? For example given the variables a and b, I would like the value 2 for cases when a=3, b=5 or b=3, a=5. Ideally I would also like to be able to vectorize the computation using the SSE registers.
The absolute difference of two real numbers x, y is given by |x − y|, the absolute value of their difference. It describes the distance on the real line between the points corresponding to x and y.
The mean absolute difference (univariate) is a measure of statistical dispersion equal to the average absolute difference of two independent values drawn from a probability distribution.
One way to find out the Absolute value of a number will be to check if the given value is negative or positive and if it's positive , then return n and if it's negative , then return n - 2*n .
the distance between two numeric values, disregarding whether this is positive or negative. The absolute difference thus provides no information about relative magnitude. For example, the absolute difference between 11 and 20 is 9, as is the absolute difference between 13 and 4.
max(i,j) - min(i,j)
(i>j)*(i-j) + (j>i)*(j-i)
you can certainly use SSE registers, but compiler may do this for you anyways
From tommesani.com, one solution for this problem is to use saturating unsigned subtraction twice.
As the saturating subtraction never goes below 0, you compute: r1 = (a-b).saturating r2 = (b-a).saturating
If a is greater than b, r1 will contain the answer, and r2 will be 0, and vice-versa for b>a. ORing the two partial results together will yield the desired result.
According to the VTUNE users manual, PSUBUSB/PSUBUSW is available for 128-bit registers, so you should be able to get a ton of parallelization this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With