# Is there a gamma function in pytorch?

**URL:** <https://discuss.pytorch.org/t/is-there-a-gamma-function-in-pytorch/17122>\
**Category:** Uncategorized\
**Created:** [April 27, 2018, 3:21pm UTC](https://discuss.pytorch.org/t/is-there-a-gamma-function-in-pytorch/17122 "2018-04-27T15:21:36Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![yxchng](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/y/7bcc69/32.png) [@yxchng](https://discuss.pytorch.org/u/yxchng)\
**Post date:** [April 27, 2018, 3:21pm UTC](https://discuss.pytorch.org/t/is-there-a-gamma-function-in-pytorch/17122/1 "2018-04-27T15:21:36Z")

</div>

I am intending to calculate factorial like in this post

> <https://stackoverflow.com/questions/47141359/how-to-calculate-factorial-in-tensorflow>

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

---

<div class="post-metadata">

**Author:** ![simonp](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/3e96dc/32.png) [@simonp](https://discuss.pytorch.org/u/simonp)\
**Post date:** [August 21, 2019, 12:07pm UTC](https://discuss.pytorch.org/t/is-there-a-gamma-function-in-pytorch/17122/2 "2019-08-21T12:07:19Z")

</div>

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

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

```

and

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

```

---

<div class="post-metadata">

**Author:** ![jasha](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jasha/32/21242_2.png) [@jasha](https://discuss.pytorch.org/u/jasha)\
**Post date:** [December 12, 2020, 7:59pm UTC](https://discuss.pytorch.org/t/is-there-a-gamma-function-in-pytorch/17122/3 "2020-12-12T19:59:21Z")

</div>

Scipy has a solution:

```auto
>>> 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.
