Skip to content
Advertisement

How to calculate factorial in tensorflow?

I am new to tensorflow, I am trying to find a function that calculates the n!. I saw that one can use the gamma function, which was possible with theano, but did not work for tensorflow.

factorial = theano.tensor.gamma(v)

I am using a for loop to multiply number from n to 1, but I assume there is an easier and faster way. I saw functions related to gamma distribution, but couldn’t figure out how to calculate the factorial. Would appreciate if one can point me to some documentation.

Here is the way I do it now

import tensorflow as tf

factorial = tf.Variable(1, "factorial")
recursion = tf.Variable(1, "recursion")

# calculate factorial
mult = tf.multiply(recursion, factorial)
assign_fact = tf.assign(factorial, mult)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init) 
    for i in range(2,10):
        counter = tf.assign(recursion, tf.constant(i))
        sess.run(counter)
        sess.run(assign_fact)

        print(i,"factorial is", sess.run(factorial))

    sess.close()

Output is

2 factorial is 2
3 factorial is 6
4 factorial is 24
5 factorial is 120
6 factorial is 720
7 factorial is 5040
8 factorial is 40320
9 factorial is 362880

Advertisement

Answer

Try this: tf.exp(tf.lgamma(x + 1)).

tf.lgamma computes the log of the absolute value of Gamma(x) element-wise, so the exponent will give you the raw Gamma(x) value:

>>> sess.run(tf.exp(tf.lgamma(5.0)))
24.0
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement