Sympy - 递归形式的算术和几何序列

Sympy - Arithmetic and geometric sequence in recursive form

我想以递归形式定义算术和几何序列,例如

在 Sympy 中,可以像这样以封闭形式定义算术序列:

from sympy import *
n = symbols('n', integer=True)
u0 = 2
r = 5
ari_seq = sequence(u0 + n * r, (n, 0, 5))

如何以递归形式 (Un+1 = Un + r) 定义(而不是求解)这个序列?

您需要使用 Function 来定义递推关系。

还有一个RecursiveSeq可能有帮助

示例:

from sympy import *
from sympy.series.sequences import RecursiveSeq

n = symbols("n", integer=True)
y = Function("y")
r, q = symbols("r, q")

# note the initial term '2' could also be symbolic
arith = RecursiveSeq(y(n-1) + r, y(n), n, [2])
geo = RecursiveSeq(y(n-1)*q, y(n), n, [2])

# calculate a few terms
arith[:5] # [2, r + 2, 2*r + 2, 3*r + 2, 4*r + 2]
geo[3:5] # [2*q**3, 2*q**4]

# to use with rsolve you'll need to unpack the RecursiveSeq into ordinary sympy expressions:
rsolve(geo.recurrence.rhs - geo.recurrence.lhs, geo.recurrence.lhs, [geo[0]])  # 2*q**n