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
bis always equal to exactly 0 or 1, and cannot be equal to other values:Only one of
band1-bwill be nonzero, so only one of the terms in the sum will be nonzero.To force
bto be equal to 0 or 1, you can use double negation!!:Or write
b == 0andb != 0explicitly:For discussion about whether
b = !!bis preferable to alternativesb = b?1:0orb = b != 0, see this answer and its comments.