Search code examples
pythonsympy

How to solve a system of equations with indexed variables in SymPy?


I have a system of equations with indexed variables. What I want is to solve the dynamic function of one variable and cancel another. For example:

from sympy import symbols, IndexedBase, Eq, solve

t = symbols('t', interger=True)
β = symbols('β')
c, λ = symbols('c λ', cls=IndexedBase)

eq1=Eq(c[t],λ[t])
eq2=Eq(λ[t],β*λ[t+1])

solve([eq1,eq2],[c[t],c[t+1]])

I get the result: {c[t]: λ[t]}. It is right, but what I really want is a function to show the relationship between c[t] and c[t+1] like c[t+1]=f(c[t]) (without λ[t]). Here, the result should be c[t+1]=1/β*c[t].

What should I do? Thank you for your help.


Solution

  • The solve function is not intended to handle situations like this. It's purpose is to solve algebraic equations and so anything like c[t] and c[t+1] are just treated as independent algebraic variables.

    You can get what you want using resultant though:

    In [15]: from sympy import symbols, IndexedBase, Eq, solve
        ...: 
        ...: t = symbols('t', interger=True)
        ...: β = symbols('β')
        ...: c, λ = symbols('c λ', cls=IndexedBase)
        ...: 
        ...: eq1=Eq(c[t],λ[t])
        ...: eq2=Eq(λ[t],β*λ[t+1])
    
    In [16]: resultant(eq1, eq2, λ[t])
    Out[16]: β⋅λ[t + 1] - c[t]
    
    In [17]: resultant(resultant(eq1, eq2, λ[t]), eq1.subs(t, t+1), λ[t + 1])
    Out[17]: β⋅c[t + 1] - c[t]
    
    In [18]: solve(_, c[t+1], dict=True)
    Out[18]: 
    ⎡⎧          c[t]⎫⎤
    ⎢⎨c[t + 1]: ────⎬⎥
    ⎣⎩           β  ⎭⎦