Search code examples
sympyequation-solvinggame-theory

SymPy cannot rearrange results while solving a system of equations about Stackelberg game


Function f (assume n=3 for simplicity): enter image description here

There are 3 symbols related to entities, corresponding to x[j](j=1,2,3) respectively. R and c is other symbols, which can be treated like constant for now. I try to diff f w.r.t x[j], and solve the results equations together and get x[j]=g(R,c). However, sympy cannot rearrange or split x[j] from the equation.

Derivatives: enter image description here

Expected Results: enter image description here

from sympy import *
import sympy as sym
real_n = 3
x = IndexedBase('x')
j, k, n = symbols('j,k n', cls=Idx)
f = x[j]*Symbol("R")/Sum(x[k],(k,1,real_n))-Symbol("c")*x[j]
equ = diff(f,x[j])

ee = solve([equ.subs(j,1),equ.subs(j,2),equ.subs(j,3)], (x[1],x[2],x[3]))
simplify(ee)

Sympy's result:

{x[1]: (R*Sum(x[k], (k, 1, 3)) - c*Sum(x[k], (k, 1, 3))**2)/(R*Sum(KroneckerDelta(1, k), (k, 1, 3))),
 x[2]: (R*Sum(x[k], (k, 1, 3)) - c*Sum(x[k], (k, 1, 3))**2)/(R*Sum(KroneckerDelta(2, k), (k, 1, 3))),
 x[3]: (R*Sum(x[k], (k, 1, 3)) - c*Sum(x[k], (k, 1, 3))**2)/(R*Sum(KroneckerDelta(3, k), (k, 1, 3)))}

enter image description here

I tried to check if the indexed symbol caused the error, and wrote x[i] as 3 different symbols, but it still didn't work.

from sympy import *

a, b, c = symbols('a b c', cls=Idx)
R = symbols("R")
eq1 = diff(a/(a+b+c)-a*R,a)
eq2 = diff(b/(a+b+c)-b*R,b)
eq3 = diff(c/(a+b+c)-c*R,c)
print(eq1,"\n",eq2,"\n",eq3)
solve([eq1,eq2,eq3], [a,b,c])

Output:

-R + 1/(a + b + c) - a/(a + b + c)**2 
 -R + 1/(a + b + c) - b/(a + b + c)**2 
 -R + 1/(a + b + c) - c/(a + b + c)**2
[]

Is there something wrong with my approach? Is it possible to approach this problem in SymPy from another angle?

Any suggestions for the solution of equations are also most welcome.


Solution

  • You can use doit to expand the summation and then solve:

    In [6]: solve([equ.subs(j,1).doit(),equ.subs(j,2).doit(),equ.subs(j,3).doit()], (x[1],x[2],x[3]))
    Out[6]: 
    ⎡⎛         ____          ⎞⎤
    ⎢⎜        ╱  2           ⎟⎥
    ⎢⎜R + 3⋅╲╱  R    2⋅R  2⋅R⎟⎥
    ⎢⎜─────────────, ───, ───⎟⎥
    ⎣⎝     18⋅c      9⋅c  9⋅c⎠⎦