Summing factorials in Python

2019-07-21 07:51发布

问题:

I would like to compute sums with factorials using symbolic algebra in python. The simplest version of the problem I can generate is the following one:

from sympy.abc import j
from math import factorial
from sympy import summation
summation(factorial(j), (j, 1, 4))

And I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "sympy/core/expr.py", line 194, in __int__
    r = self.round(2)
  File "sympy/core/expr.py", line 3042, in round
    raise TypeError('%s is not a number' % type(x))
TypeError: <class 'sympy.core.symbol.Symbol'> is not a number

Fundamentally, what I would like to compute is

summation(x**(j-1)/factorial(j-1), (j, 1, 3))

Any suggestion?

回答1:

Using Sympy's own factorial function (instead of the math module's factorial function) could perhaps return what you want.

Following your initial setup but omitting from math import factorial, you could then write:

>>> from sympy import factorial, symbols
>>> x = symbols('x')
>>> summation(x**(j-1)/factorial(j-1), (j, 1, 3))
x**2/2 + x + 1

This reduces the summation of the factorial series to a simple quadratic equation.

I notice you are calculating the sum of the first few terms of the power series expansion of exp(x):

1 + x + x**2/2! + x**3/3! + ...


回答2:

The only solution I can think of avoiding loops is a functional version :S:

from math import factorial

reduce(int.__add__,map(factorial,xrange(1,5)))