0
0
SciPydata~5 mins

Factorial and gamma functions in SciPy

Choose your learning style9 modes available
Introduction

We use factorial and gamma functions to count things and work with special math problems. They help us find the product of numbers in a simple way.

When you want to find the number of ways to arrange items (like seating people).
When calculating probabilities in statistics, like combinations.
When working with continuous extensions of factorials for non-integers.
When solving problems involving growth or decay that use special math functions.
When you need to compute factorials for large numbers efficiently.
Syntax
SciPy
from scipy.special import factorial, gamma

factorial(n, exact=False)
gamma(x)

factorial(n) calculates n! (n factorial), the product of all positive integers up to n.

gamma(x) extends factorial to real and complex numbers, where gamma(n) = (n-1)! for positive integers.

Examples
Calculates 5! = 120.
SciPy
from scipy.special import factorial
print(factorial(5))
Calculates exact integer factorial of 5.
SciPy
from scipy.special import factorial
print(factorial(5, exact=True))
Calculates gamma(6) which equals 5! = 120.
SciPy
from scipy.special import gamma
print(gamma(6))
Calculates gamma for a non-integer value 2.5.
SciPy
from scipy.special import gamma
print(gamma(2.5))
Sample Program

This program shows how to calculate factorial exactly, gamma for an integer, and gamma for a non-integer value.

SciPy
from scipy.special import factorial, gamma

# Calculate factorial of 7
fact_7 = factorial(7, exact=True)

# Calculate gamma of 8 (which is 7!)
gamma_8 = gamma(8)

# Calculate gamma for a non-integer
gamma_4_5 = gamma(4.5)

print(f"7! (factorial) = {fact_7}")
print(f"Gamma(8) = {gamma_8}")
print(f"Gamma(4.5) = {gamma_4_5:.4f}")
OutputSuccess
Important Notes

Use exact=True in factorial to get an integer result, otherwise it returns a float.

Gamma function works for non-integers and extends factorial to real numbers.

Factorial is only defined for non-negative integers, but gamma works for many more values.

Summary

Factorial counts the product of all positive integers up to a number.

Gamma function extends factorial to real and complex numbers.

Use scipy.special to easily calculate both in Python.