Python Numpy Factorial

Recently, I was working on a data science project where I needed to calculate factorials for a large array of values. The issue is, calculating factorials one by one using traditional Python methods can be quite slow for large datasets. This is where NumPy’s factorial functions become incredibly useful.

In this article, I will cover five simple ways you can use to calculate factorials in NumPy (including the standard method, vectorized operations, and some advanced techniques).

So let’s dive in!

NumPy Factorial

Before we get into the methods, let’s quickly review what factorial is. The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

NumPy provides efficient ways to calculate factorials, especially when dealing with arrays of numbers, which is much faster than using Python’s built-in math module for multiple calculations.

Read Create a Matrix in Python

Calculate factorials in NumPy

Let me explain how to calculate factorials in Python NumPy using all efficient methods.

Method 1 – Use numpy.factorial()

The simplest way to calculate factorials in NumPy is by using the numpy.factorial() function in Python. This function can handle both single values and arrays.

import numpy as np
from scipy.special import factorial

# For a single value
result = factorial(5, exact=True)
print(f"Factorial of 5 is: {result}")

# For an array of values
numbers = np.array([0, 1, 2, 3, 4, 5])
result_array = factorial(numbers, exact=True)
print(f"Factorials of [0,1,2,3,4,5]: {result_array}")

Output:

Factorial of 5 is: 120
Factorials of [0,1,2,3,4,5]: [  1   1   2   6  24 120]

I executed the above example code and added the screenshot below.

NumPy factorial

This method is clean, efficient, and works for most common factorial calculations. It’s my go-to method when working with moderate-sized datasets.

Check out Random Number Between Two Values in Numpy

Method 2 – Use numpy.math.factorial()

Python NumPy also provides a math module with a factorial function that works slightly differently from the main numpy.factorial():

import numpy as np
import math

# Single value calculation
result = math.factorial(5)
print(f"Factorial of 5 is: {result}")

# Apply to each element in an array
factorial_func = np.vectorize(math.factorial)
numbers = np.array([0, 1, 2, 3, 4, 5])
result_array = factorial_func(numbers)
print(f"Factorials of [0,1,2,3,4,5]: {result_array}")

Output:

Factorial of 5 is: 120
Factorials of [0,1,2,3,4,5]: [  1   1   2   6  24 120]

I executed the above example code and added the screenshot below.

factorial NumPy

The key difference here is that we need to use np.vectorize() to apply the function to an array, which makes this method slightly less convenient than the first one for array operations.

Read Create a Python Empty Matrix

Method 3 – Use scipy.special.factorial()

SciPy’s special module offers another factorial function that can handle decimal and negative inputs by using the gamma function:

from scipy import special
import numpy as np

# For a single value
result = special.factorial(5)
print(f"Factorial of 5 is: {result}")

# For an array of values
numbers = np.array([0, 1, 2, 3, 4, 5])
result_array = special.factorial(numbers)
print(f"Factorials of [0,1,2,3,4,5]: {result_array}")

# Works with decimal values too
result_decimal = special.factorial(4.5)
print(f"Factorial of 4.5 is approximately: {result_decimal}")

Output:

Factorial of 5 is: 120.0
Factorials of [0,1,2,3,4,5]: [  1.   1.   2.   6.  24. 120.]
Factorial of 4.5 is approximately: 52.34277778455352

I executed the above example code and added the screenshot below.

factorial in NumPy

I find this method particularly useful when I need to calculate factorials of non-integer values, which the standard NumPy factorial function doesn’t support.

Check out NumPy Reset Index of an Array in Python

Method 4 – Use numpy.cumprod() for Custom Implementation

If you need more control over the factorial calculation or want to implement custom logic, you can use NumPy’s cumprod() function:

import numpy as np

def custom_factorial(n):
    if n == 0:
        return 1
    return np.cumprod(np.arange(1, n+1))[-1]

# For a single value
result = custom_factorial(5)
print(f"Factorial of 5 is: {result}")

# For multiple values using list comprehension
numbers = np.array([0, 1, 2, 3, 4, 5])
result_array = np.array([custom_factorial(num) for num in numbers])
print(f"Factorials of [0,1,2,3,4,5]: {result_array}")

Output:

Factorial of 5 is: 120
Factorials of [0,1,2,3,4,5]: [  1   1   2   6  24 120]

This approach gives you flexibility to modify the factorial calculation logic if needed. For example, you could add overflow prevention, custom rounding, or other special handling.

Read np.genfromtxt() Function in Python

Method 5 – Use gamma Function for Large Factorials

For very large factorials where overflow might be a concern, you can use the gamma function, which is related to factorial by: n! = Γ(n+1)

import numpy as np
from scipy import special

# For a single large value
n = 100
# Using log to avoid overflow
result = np.exp(special.gammaln(n+1))
print(f"Factorial of 100 is approximately: {result:.2e}")

# For an array of large values
numbers = np.array([50, 100, 150])
result_array = np.exp(special.gammaln(numbers+1))
print(f"Factorials of large numbers: {result_array}")

Output:

Factorial of 100 is approximately: 9.33e+157
Factorials of large numbers: [3.04141e+64 9.33262e+157 5.71338e+262]

This method is particularly useful when working with statistical distributions or calculations that involve very large factorials that might cause numerical overflow in standard methods.

Check out np.savetxt() Function in Python

Real-world Application: Calculate Binomial Coefficients

Let’s look at a practical example. Suppose you’re analyzing customer data for a US retail chain, and you need to calculate the number of possible ways to select k items from n products for a promotional campaign.

This requires calculating binomial coefficients, which involve factorials:

import numpy as np

def binomial_coefficient(n, k):
    # Calculate n choose k using factorials
    return np.factorial(n) // (np.factorial(k) * np.factorial(n - k))

# Calculate ways to select 3 products from a set of 10 for a promotion
result = binomial_coefficient(10, 3)
print(f"Number of ways to select 3 products from 10: {result}")

# Calculate for multiple selection sizes
k_values = np.array([2, 3, 4, 5])
results = np.array([binomial_coefficient(10, k) for k in k_values])
print(f"Selection options for different k values: {results}")

Output:

Number of ways to select 3 products from 10: 120
Selection options for different k values: [ 45 120 210 252]

This shows the power of NumPy’s factorial function in real-world scenarios like retail analytics or marketing campaign planning.

Read NumPy Array to List in Python

Numpy Factorial Example

This example demonstrates how to create a simple GUI application for calculating factorials using Python’s Tkinter library. While the code uses the math.factorial() function from Python’s standard library rather than NumPy’s factorial function, it could be easily modified to use numpy.math.factorial() instead.

import math
from tkinter import *

f = ('sans-serif', 14)
ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws.config(bg='#F27405')

def cal_factorial():
    user_input = entry.get()
    try:
        num = int(user_input)
        if num < 0:
            result_label.config(text="Please enter a non-negative number.")
        else:
            res = math.factorial(num)
            result_label.config(text=f"Factorial of {num} is: {res}")
    except ValueError:
        result_label.config(text="Invalid input. Enter a whole number.")

Label(
    ws, 
    text='Factorial Calculator',
    font=('sans-serif', 22),
    relief=SOLID,
    padx=10,
    pady=10
).pack(pady=10)

Label(
    ws, 
    text='Enter Number',
    font=f,
    bg='#F27405'
).pack(pady=(10, 0))

entry = Entry(ws, font=f)
entry.pack()

Button(
    ws, 
    text='Calculate', 
    command=cal_factorial,
    font=f,
    bg='#060126',
    fg='white'
).pack(pady=(10, 0))

result_label = Label(ws, text="", font=f, bg='#F27405')
result_label.pack(pady=(10, 0))

ws.mainloop()

You can see the output in the screenshot below.

Numpy Factorial Example

The program is built around these key components:

  1. UI Setup: Creates a window with an entry field, a button, and a result label
  2. Error Handling: Validates input to ensure it’s a non-negative integer
  3. Calculation Logic: Uses factorial function to compute the result

When a user enters a number and clicks “Calculate”, the application converts the input to an integer, calculates its factorial, and displays the result. The factorial of a number (like 5! = 5×4×3×2×1 = 120) is computed efficiently using the built-in function.

I hope you found this article helpful! NumPy’s factorial functions are incredibly powerful tools when working with data science problems that involve combinatorial calculations. The right method depends on your specific needs – whether you’re dealing with large numbers, non-integer values, or need specialized control over the calculation process.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.