Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the nth term of a generating function using sympy?

I have a rational function: f(x) = P(x)/Q(x). For example:

f(x) = (5x + 3)/(1-x^2)

Because f(x) is a generating function it can be written as:

f(x) = a0 + a1*x + a2*x² + ... + a_n*x^n + ... = P(x)/Q(x)

How can I use sympy to find the nth term of the generating function f(x) (that is a_n)?

If there is no such implementation in Sympy, I am curious also to know if this implemented in other packages, such as Maxima.

I appreciate any help.


2 Answers

To get the general formula for a_n of the generating function of a rational form , SymPy's rational_algorithm can be used. For example:

from sympy import simplify
from sympy.abc import x, n
from sympy.series.formal import rational_algorithm

f = (5*x + 3)/(1-x**2)
func_n, independent_term, order = rational_algorithm(f, x, n, full=True)
print(f"The general formula for a_n is {func_n}")
for k in range(10):
    print(f"a_{k} = {simplify(func_n.subs(n, k))}")

Output:

The general formula for a_n is (-1)**(-n - 1) + 4
a_0 = 3
a_1 = 5
a_2 = 3
a_3 = 5
a_4 = 3
a_5 = 5
a_6 = 3
a_7 = 5
a_8 = 3
a_9 = 5

Here is another example:

f = x / (1 - x - 2 * x ** 2)
func_n, independent_term, order = rational_algorithm(f, x, n, full=True)
print(f"The general formula for a_n is {func_n.simplify()}")
print("First terms:", [simplify(func_n.subs(n, k)) for k in range(20)])
The general formula for a_n is 2**n/3 - (-1)**(-n)/3
First terms: [0, 1, 1, 3, 5, 11, 21, 43, 85, 171, 341, 683, 1365, 2731, 5461, 10923, 21845, 43691, 87381, 174763]
like image 89
JohanC Avatar answered Oct 22 '25 05:10

JohanC


You could take the kth derivative and substitute 0 for x and divide by factorial(k):

>>> f = (5*x + 3) / (1-x**2)
>>> f.diff(x, 20).subs(x, 0)/factorial(20)
3

The reference here talks about rational generating functions. Looking for a recurrence you can see the pattern pretty quickly using differentiation:

[f.diff(x,i).subs(x,0)/factorial(i) for i in range(6)]
[3, 5, 3, 5, 3, 5]
like image 34
smichr Avatar answered Oct 22 '25 04:10

smichr