[英]Why is a / (b*c) slower than a / b / c in Python (and in general)?
I stumbled across an interesting optimization question while writing some mathematical derivative functions for a neural network library.在为神经网络库编写一些数学导数函数时,我偶然发现了一个有趣的优化问题。 Turns out that the expression a / (b*c)
takes longer to compute than a / b / c
for large values (see timeit
below).事实证明,对于大值,表达式a / (b*c)
比a / b / c
需要更长的时间来计算(请参见下面的timeit
)。 But since the two expressions are equal:但由于这两个表达式是相等的:
a / (b*c)
, given that it seems to be slower?是否有 a a / (b*c)
,因为它似乎更慢?Thanks in advance :)提前致谢 :)
In [2]: timeit.timeit('1293579283509136012369019234623462346423623462346342635610 / (52346234623632464236234624362436234612830128521357*32189512234623462637501237)')
Out[2]: 0.2646541080002862
In [3]: timeit.timeit('1293579283509136012369019234623462346423623462346342635610 / 52346234623632464236234624362436234612830128521357 / 32189512234623462637501237')
Out[3]: 0.008390166000026511
Why is a/(b*c)
slower?为什么a/(b*c)
更慢?
(b*c)
is multiplying two very big ints with unlimited precision. (b*c)
以无限精度乘以两个非常大的整数。 That is a more expensive operation than performing floating point division (which has limited precision).这是比执行浮点除法(精度有限)更昂贵的操作。
Are the two calculations equivalent?这两个计算是等价的吗?
In practice, a/(b*c)
and a/b/c
can give different results, because floating point calculations have inaccuracies, and doing the operations in a different order can produce a different result.在实践中, a/(b*c)
和a/b/c
会给出不同的结果,因为浮点计算有不准确的地方,以不同的顺序进行运算会产生不同的结果。
For example:例如:
a = 10 ** 33
b = 10000000000000002
c = 10 ** 17
print(a / b / c) # 0.9999999999999999
print(a / (b * c)) # 0.9999999999999998
It boils down to how a computer deals with the numbers it uses.它归结为计算机如何处理它使用的数字。
Why doesn't Python calculate a/(b*c)
as a/b/c
?为什么 Python 不将a/(b*c)
为a/b/c
?
That would give surprising results.那会产生出人意料的结果。 The user ought to be able to expect that用户应该能够期望
d = b*c
a / d
should have the same result as应该有相同的结果
a / (b*c)
so it would be a source of very mysterious behaviour if a / (b*c)
gave a different result because it was magically replaced by a / b / c
.所以如果a / (b*c)
给出不同的结果,因为它被a / b / c
神奇地取代了,这将是一个非常神秘的行为来源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.