Binomial Coefficient in Python

Binomial Coefficient in Python

Shivam Arora Oct-19, 2021 Jul-02, 2021 Python Python Math
  1. Use the scipy Module to Calculate the Binomial Coefficient in Python
  2. Use the math.comb() Function to Calculate the Binomial Coefficient in Python
  3. Use the operator Module to Calculate the Binomial Coefficient in Python
  4. Use the math.fact() Function to Calculate the Binomial Coefficient in Python

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.

Use the scipy Module to Calculate the Binomial Coefficient in Python

SciPy 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

Use the math.comb() Function to Calculate the Binomial Coefficient in Python

The 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

Use the operator Module to Calculate the Binomial Coefficient in Python

In 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

Use the math.fact() Function to Calculate the Binomial Coefficient in Python

We 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

Related Article - Python Math

  • Calculate Factorial in Python
  • Calculate Inverse of Cosine in Python
  • Calculate Modular Multiplicative Inverse in Python
  • Fit Poisson Distribution to Different Datasets in Python
  • Reduce Fractions in Python
  • Define an Infinite Value in Python