Summing factorials in Python

谁说我不能喝 提交于 2019-12-24 05:32: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)))


来源:https://stackoverflow.com/questions/28583674/summing-factorials-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!