将false/true转换为-1/+ 1的无分支方法? [英] Branchless method to convert false/true to -1/+1?

查看:75
本文介绍了将false/true转换为-1/+ 1的无分支方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行以下映射的无分支方式是什么?

What is a branchless way to do the following mapping?

true -> +1
false -> -1

一种简单的方法是 if b then 1 else -1 ,但是我正在寻找一种避免分支的方法,即if.

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.

如果相关,我正在使用Python.

If it is relevant, I'm using Python.

推荐答案

您可以利用以下事实:在Python中,类型 bool 是数字:

You can exploit the fact that in Python, the type bool is numeric:

>>> True == 1
True
>>> False == 0
True

因此表达式 2 * b-1 给出了所需的结果:

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

但是,即使这是否真的是无分支的"也有争议.它将被编译成Python字节码而没有条件跳转,但是字节码解释器肯定会执行一些条件跳转才能执行它:至少,它必须检查要执行的操作码,的操作数类型* -具有,依此类推.

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.

这篇关于将false/true转换为-1/+ 1的无分支方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆