ID : 357

viewed : 65

Tags : PythonPython Math

96

Mathematically speaking, the binomial coefficient is the number of combinations of `r`

number of items that could be used to form a set of `n`

items, or we could say that this coefficient is the number of ways of selecting outcomes in an unordered way from possibilities.

In this article, we will calculate the binomial coefficient in Python.

`scipy`

Module to Calculate the Binomial Coefficient in PythonSciPy has two methods to calculate the binomial coefficients. The first function is called `scipy.special.binom()`

. This function generally handles large values efficiently.

For example,

`import scipy.special print(scipy.special.binom(10,5)) `

Output:

`252.0 `

The second function that returns the binomial coefficient is called `scipy.special.comb()`

.

For example,

`import scipy.special print(scipy.special.comb(10,5)) `

Output:

`252.0 `

`math.comb()`

Function to Calculate the Binomial Coefficient in PythonThe `comb()`

function from the `math`

module returns the combination of the given values, which essentially has the same formula as the binomial coefficient. This method is an addition to recent versions of Python 3.8 and above.

For example,

`import math print(math.comb(10,5)) `

Output:

`252 `

`operator`

Module to Calculate the Binomial Coefficient in PythonIn older versions of Python, `math.factorial`

is not present and thus, could not be used. To compensate for this and generate the output in much less time, we can use the `math`

and `operator`

modules together.

A lambda function product is created with `operator.mul`

to get the product of numbers.

For example,

`import math import operator from functools import reduce product = lambda m,n: reduce(operator.mul, range(m, n+1), 1) x = 10 y = 5 product(y+1, x) / product(1, x-y) `

Output:

`252 `

`math.fact()`

Function to Calculate the Binomial Coefficient in PythonWe can use the `fact()`

function from the `math`

module to implement the mathematical formula for calculating the binomial coefficient.

See the code below.

`from math import factorial as fact def binomial(n, r): return fac(n) // fac(r) // fac(n - r) print(binomial(10,5)) `

Output:

`252 `