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.
JavaScript
x
2
1
factorial = theano.tensor.gamma(v)
2
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
JavaScript
1
22
22
1
import tensorflow as tf
2
3
factorial = tf.Variable(1, "factorial")
4
recursion = tf.Variable(1, "recursion")
5
6
# calculate factorial
7
mult = tf.multiply(recursion, factorial)
8
assign_fact = tf.assign(factorial, mult)
9
10
init = tf.global_variables_initializer()
11
12
with tf.Session() as sess:
13
sess.run(init)
14
for i in range(2,10):
15
counter = tf.assign(recursion, tf.constant(i))
16
sess.run(counter)
17
sess.run(assign_fact)
18
19
print(i,"factorial is", sess.run(factorial))
20
21
sess.close()
22
Output is
JavaScript
1
9
1
2 factorial is 2
2
3 factorial is 6
3
4 factorial is 24
4
5 factorial is 120
5
6 factorial is 720
6
7 factorial is 5040
7
8 factorial is 40320
8
9 factorial is 362880
9
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:
JavaScript
1
3
1
>>> sess.run(tf.exp(tf.lgamma(5.0)))
2
24.0
3