What is a branchless way to do the following mapping?
true -> +1
false -> -1
An easy way would be if b then 1 else -1
but I'm looking for a method to avoid the branch, i.e. if.
If it is relevant, I'm using Python.
You can exploit the fact that in Python, the type bool
is numeric:
>>> True == 1
True
>>> False == 0
True
So the expression 2 * b - 1
gives the desired results:
>>> def without_branching(b):
... return 2 * b - 1
...
>>> without_branching(True)
1
>>> without_branching(False)
-1
However, it's arguable whether even this is really "branchless". It will be compiled to Python bytecode with no conditional jumps, but the bytecode interpreter will certainly do some conditional jumps in order to execute it: at the very least, it has to check which opcodes to execute, what types the operands of *
and -
have, and so on.