Search code examples
pythonsympymathematical-optimization

Why does sympy.solve not output anything?


I am trying to solve a system of equations. The equations in the example below are the first derivatives of a Lagrangian function (LDash 1 through 7), which I obtained by pen and paper. The solutions to the system should give the candidates for maxima and minima.

The choice variables are X1, X2, LC, LA, s, u, while all other symbols are place holders for positive reals.

The script runs but then doesn't display anything in my console. In the examples throughout the SymPy documentation solve outputs the solution. Can you help me find out why it does not do that in my example below?

I am completely new to Python, so please let me know how I can improve. Thanks!

# import stuff
from sympy.interactive import printing
printing.init_printing(use_latex=True)
from sympy import Function
from sympy.solvers import solve
import sympy as sp

X1, X2, LC, LA, s, u = sp.var('X_1, X_2, L_C, L_A, s, u', positive=True);

# import exogenous variables

a1, a2, a3, a4, S1, S2, S3, S4, p1, p2, p3, p4, fdash, vdash,f, v = sp.symbols('alpha_1, alpha_2, alpha_3, alpha_4, S_1, S_2, S_3, S_4, p_1, p_2, p_3, p_4, \hat{F}, \hat{V}, f, v', positive=True)

v0 = sp.symbols('v_0') # raw skill level
i = sp.symbols('\hat{\imath}') # children in the household - time endowment
I = sp.symbols('I') # household size and total time endowment
climate = sp.symbols('theta') # climate variable
capital = sp.symbols('K') # quasi fixed land and (non-human) capital
lam = sp.symbols('\lambda') # shadow prices (lagrange multiplier)

# pen-and-paper: derivatives of the Lagrange function w.r.t choice variables

LDash1 = a1/(X1-S1)-lam*p1 # L' w.r.t X1
LDash2 = a2/(X2-S2)-lam*p2 # L' w.r.t X2
LDash3 = -a3/(I-i-LA-S3) + 2*lam*p3 + lam*p1*fdash # L' w.r.t LA
LDash4 = -1/(i-LC) - a4/(i-LC-S4) + 2*lam*p4 + lam*p1*fdash*(-s*u + s*v +(1-s)*v0) # L' w.r.t LC
LDash5 = lam*p1*fdash *(-u*LC + v*LC - v0*LC) # L' w.r.t. s
LDash6 = lam*p1*fdash *(-s*LC + s*vdash*LC) # L' w.r.t u
LDash7 = p1*X1 + p2*X2 -2*p3*I + 2*p3*i + 2*p3*LA -2*p4*i + 2*p4*LC + p1*f # L' w.r.t lambda

solve((LDash1,LDash2, LDash3, LDash4, LDash5, LDash6, LDash7), (X1,X2,LA,LC,u,s))

Solution

  • You have two problems, firstly the solve call will take a very long time and potentially not return successfully at all. Secondly even if it would return, say you replace the call with solve(LDash1, X1) the return value of solve is never printed. Try to replace the last line with this for example to be able to debug your equations

    solve(LDash1, X1)
    

    The reason the answer is printed in the documentation is because they use interactive mode, this is normally indicated by the Python interactive prompt >>>