I'm writing a program that is doing some geometric calculations and I have a certain calculation where I need to multiply either by a fraction a
or by 1-a
given the value of a certain flag. Here's some pseudocode to help illustrate.
switch b
case 0:
return w*a
case 1:
return w*(1-a)
(In context this isn't an entire function, it's just done inlined obviously, but this is the only context required for the question)
I'm curious if there is a way to calculate this value using the value of the flag b
with basic arithmetic operations etc for a branchless approach. The best I've come up with so far is !b*w*a + b*w*(1-a)
, but that feels like a cop-out lol.
My next best approach was w*abs(a-b)
, but this would require an abs
function that also meets the specification.
This isn't very performance critical and even if it was I'm sure my 'cop-out' would suffice, but I'm asking more as a curiosity :)
Assuming flag b
is always equal to exactly 0 or 1, and cannot be equal to other values:
return w * (b * a + (1 - b) * (1 - a))
Only one of b
and 1-b
will be nonzero, so only one of the terms in the sum will be nonzero.
To force b
to be equal to 0 or 1, you can use double negation !!
:
b = !!b
return w * (b * a + (1 - b) * (1 - a))
Or write b == 0
and b != 0
explicitly:
return w * ((b != 0) * a + (b == 0) * (1 - a))
For discussion about whether b = !!b
is preferable to alternatives b = b?1:0
or b = b != 0
, see this answer and its comments.