Is there a gamma function in pytorch?

I am intending to calculate factorial like in this post

I am just wondering if I can not use math.factorial?

2 Likes

I know this conversation is old, but maybe it still helps someone: Just like in TensorFlow, you can use lgamma, the log of the gamma function, to calculate the factorial, as n! == gamma(n+1) == exp(lgamma(n+1)) for integers n.

Compare

from math import factorial
print([factorial(n) for n in range(5)])
>>> [1, 1, 2, 6, 24]

and

import torch
print((torch.arange(5) + 1).to(torch.float).lgamma().exp())
>>> tensor([ 1.,  1.,  2.,  6., 24.])
5 Likes

Scipy has a solution:

>>> import scipy.special
>>> import torch
>>> arr = torch.arange(5)
>>> arr
tensor([0, 1, 2, 3, 4])
>>> scipy.special.factorial(arr)
tensor([ 1.,  1.,  2.,  6., 24.], dtype=torch.float64)

This does not work with backprop / autograd, however.