简体   繁体   English

计算倒数:n **(-1)或(1 / n)?

[英]Calculating Reciprocals: n**(-1) or (1/n)?

In random.py's source code, there is the following constant definition: 在random.py的源代码中,有以下常量定义:

BPF = 53        # Number of bits in a float
RECIP_BPF = 2**-BPF

I'm no math major, but isn't it more readable to invert BPF by placing a 1 over it? 我不是数学专业的学生,​​但是通过在其上放一个1来反转BPF难道不是更容易理解吗?

Or is there something about multiplication that is more convenient than division in programming? 还是在编程中比乘法更方便的事?


Nevermind. 没关系。

In an effort to clean up my question I found this: 为了清理我的问题,我发现了这一点:

"On many machines, particularly those without hardware support for division, division is a slower operation than multiplication, so this approach can yield a considerable speedup. The first step is relatively slow but only needs to be done once." “在许多机器上,尤其是那些没有硬件支持除法的机器,除法运算比乘法运算要慢,因此这种方法可以大大提高速度。第一步相对较慢,但只需要执行一次。”

http://en.wikipedia.org/wiki/Multiplicative_inverse http://en.wikipedia.org/wiki/Multiplicative_inverse

RECIP_BPF , despite its name, is not 1/BPF. RECIP_BPF ,尽管其名称不为1 / BPF。 It is 1/(2^BPF). 它是1 /(2 ^ BPF)。 I can't speak for everyone, but I find it easier to read as 2**-BPF than I would as 1.0/2**BPF . 我不能代表所有人,但是我发现2**-BPF1.0/2**BPF更容易阅读。

Note that the speed of multiplication and division is not really relevant here; 注意,乘法和除法的速度在这里并不重要。 in particular, since these are constants, a compiler or interpreter only needs to evaluate them once (and a compiler can even do it at compile time). 特别是,由于这些是常量,因此编译器或解释器只需要对它们进行一次评估(并且编译器甚至可以在编译时进行评估)。 Moreover, since these are exact powers of two, there are direct ways to produce the result without doing either multiplication or division, using the fact that floating-point uses a binary encoding. 此外,由于这是2的精确乘方,因此存在直接的方法可以使用浮点使用二进制编码的事实而无需进行乘法或除法来产生结果。

“ 2 **-BPF”表示2提升到-BPF的幂。

Redability is subjective. 可重复性是主观的。 That said, I personally find 2**-BPF easier to read than 1.0/2**BPF (with or without parentheses around 2**BFP ). 就是说,我个人觉得2**-BPF1.0/2**BPF更容易阅读(带或不带括号的2**BFP )。

As to performance differences, I doubt they are relevant since the expression is only evaluated once, when the module is imported. 至于性能差异,我怀疑它们是否相关,因为在导入模块时,该表达式仅被评估一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM