开发者

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

开发者 https://www.devze.com 2023-04-07 21:29 出处:网络
In random.py\'s source code, there is the following constant definition: BPF = 53# Number of bits in a float

In random.py's source code, there is the following constant definition:

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?

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


RECIP_BPF, despite its name, is not 1/BPF. It is 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.

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.


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).

As to performance differences, I doubt they are relevant since the expression is only evaluated once, when the module is imported.


"2**-BPF" means 2 raised to the -BPF power.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号