SymPy: solving a system of equation and replacing the values in the original expression

sylvaticus
Fri, 27 Jan 2023 17:59:05 +0000
General Usage

Hello, I am trying to replicate this (old) simple example on symbolically finding the resolution of a system of equations and replacing an expression with the founded numerical solution:

I arrived to it by manually recreating the dictionary, but is it not possible to have the symbol names from the output of solve as before ?

julia> using SymPy

julia> @vars x y w l1 l2
(x, y, w, l1, l2)

julia> lagr = 2x + 4y + y * w + l1 * (6 - 2x * w) + l2 * (9 - x - y * w)
l₁⋅(-2⋅w⋅x + 6) + l₂⋅(-w⋅y - x + 9) + w⋅y + 2⋅x + 4⋅y

julia> dlx = diff(lagr,x)
-2⋅l₁⋅w - l₂ + 2

julia> dly = diff(lagr,y)
-l₂⋅w + w + 4

julia> dlw = diff(lagr,w)
-2⋅l₁⋅x - l₂⋅y + y

julia> dll1 = diff(lagr,l1)
-2⋅w⋅x + 6

julia> dll2 = diff(lagr,l2)
-w⋅y - x + 9

julia> sola = solve([dlx, dly, dlw, dll1, dll2],[x, y, w, l1, l2])
1-element Vector{NTuple{5, Sym}}:
 (39/8, 429/64, 8/13, -143/32, 15/2)

julia> solb = nonlinsolve((dlx, dly, dlw, dll1, dll2),(x, y, w, l1, l2))
⎧⎛      429        -143       ⎞⎫
⎨⎜39/8, ───, 8/13, ─────, 15/2⎟⎬
⎩⎝       64          32       ⎠⎭

julia> sol = Dict([k=>v for (k,v) in zip([x,y,w,l1,l2],sola[1])])
Dict{Sym, Sym} with 5 entries:
  w  => 8/13
  l1 => -143/32
  y  => 429/64
  x  => 39/8
  l2 => 15/2

julia> z = lagr.evalf(subs=sol)
40.6875000000000

2 posts - 1 participant