用Python总结阶乘 [英] Summing factorials in Python

查看:99
本文介绍了用Python总结阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python中的符号代数来计算阶乘和.我可以生成的最简单的问题是以下版本:

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))

然后出现以下错误:

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))

有什么建议吗?

推荐答案

使用Sympy自己的factorial函数(而不是math模块的阶乘函数)可能会返回您想要的内容.

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

在完成初始设置但省略from math import factorial之后,您可以这样写:

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.

我注意到您正在计算exp(x)的幂级数展开的前几个项的总和:

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! + ...

这篇关于用Python总结阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆