Skip to main content
 首页 » 编程设计

python之比较 python 阶乘的性能(数学与 scipy)

2025年05月04日21Leo_wl

为什么 math.factorial 比 scipy.special.factorial 快这么多?

import timeit 
 
t = timeit.timeit("from math import factorial; factorial(20)"); print(t) 
0.6399730000412092 
 
t = timeit.timeit("from scipy.special import factorial; factorial(20)"); print(t) 
5.339432950946502 
 
t = timeit.timeit("from scipy.special import factorial; factorial(20, exact=True)"); print(t) 
1.7984685270348564 

我使用的是 Python 3.7(scipy 版本是 1.1.0)

请您参考如下方法:

这是一个常见的错误,类似于期望像 np.exp() 这样的东西比 math 模块运行得更快。这不是此类功能的目的。科学堆栈(NumPy、Pandas、SciPy 等)关注的是跨数组的向量化方法,而不是单个值。

from math import factorial 
 
factorial([20, 20, 20]) 

这将给出 TypeError: an integer is required (got type list)

但是:

from scipy.special import factorial 
 
factorial([20, 20, 20]) 

将计算整个列表的阶乘,给出:

array([2.43290201e+18, 2.43290201e+18, 2.43290201e+18]) 

如果您将 math.factorial 计算放到 for 循环中以覆盖列表中的多个项目,它会很快落后于矢量化方法的计时(如果您首先提供 NumPy 数组而不是列表,这会更快)