Python 中的二项式系数
    
    
            Shivam Arora
    2023年10月10日
    
    Python
    Python Math
    
- 
          
            在 Python 中使用 scipy模块计算二项式系数
- 
          
            在 Python 中使用 math.comb()函数计算二项式系数
- 
          
            在 Python 中使用 operator模块计算二项式系数
- 
          
            在 Python 中使用 math.fact()函数计算二项式系数
 
从数学上讲,二项式系数是 r 个项目的组合数,可用于形成一组 n 个项目,或者我们可以说这个系数是在无序中选择结果的方式的数量从可能性的方式。
在本文中,我们将在 Python 中计算二项式系数。
在 Python 中使用 scipy 模块计算二项式系数
SciPy 有两种方法来计算二项式系数。第一个函数称为 scipy.special.binom()。此函数通常有效地处理大值。
例如,
import scipy.special
print(scipy.special.binom(10, 5))
输出:
252.0
返回二项式系数的第二个函数称为 scipy.special.comb()。
例如,
import scipy.special
print(scipy.special.comb(10, 5))
输出:
252.0
在 Python 中使用 math.comb() 函数计算二项式系数
math 模块中的 comb() 函数返回给定值的组合,该组合本质上与二项式系数具有相同的公式。此方法是对 Python 3.8 及更高版本的最新版本的补充。
例如,
import math
print(math.comb(10, 5))
输出:
252
在 Python 中使用 operator 模块计算二项式系数
在旧版本的 Python 中,math.factorial 不存在,因此无法使用。为了弥补这一点并在更短的时间内生成输出,我们可以一起使用 math 和 operator 模块。
使用 operator.mul 创建一个 lambda 函数乘积以获取数字的乘积。
例如,
import math
import operator
from functools import reduce
def product(m, n):
    return reduce(operator.mul, range(m, n + 1), 1)
x = 10
y = 5
product(y + 1, x) / product(1, x - y)
输出:
252
在 Python 中使用 math.fact() 函数计算二项式系数
我们可以使用 math 模块中的 fact() 函数来实现计算二项式系数的数学公式。
请参考下面的代码。
from math import factorial as fact
def binomial(n, r):
    return fac(n) // fac(r) // fac(n - r)
print(binomial(10, 5))
输出:
252
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe