Sympy Solve Examples
A few calculus tasks
- Solve for the variable
- Solve for $y$ in terms of the other variables
- Find the $x$ intercepts
- Multivariable optimization: Lagrange Multipliers
from sympy import *
init_printing()
t=symbols("t")
expr=2/(t-4)+3/(t+4) + 8/((t-4)*(t+4))
tsol=solve(expr,t,dict=True)
tsol
And just 'cause we can, let's verify the solution by plugging it into the original expression:
expr.subs(tsol[0])
x,y = symbols("x,y")
ysol=solve(Eq(1/2*x*y+y,3*x-2*y),y,dict=True)
ysol
(1/2*x*y+y).subs(ysol[0]) - (3*x-2*y).subs(ysol[0])
factor(_)
ee=Eq(y,x**2+3*x+2)
ee
ee.subs(y,0)
solve(_,x)
Minimize the function $f(x)=2x^2+y^2$ subject to the constraint $x^2+y^2=1$
x,y = symbols("x y")
h = symbols("h") # h is the lagrange multipler
f=2*x**2 + y**2
g=x**2+y**2
s=solve([Eq(f.diff(x),h*g.diff(x)),
Eq(f.diff(y),h*g.diff(y)),
Eq(g,1)],[x,y,h],
dict=True)
s
We evaluate the objective function $f$ at each of the points identified by the Lagrang multiplier procedure and see that minimum value of $f$ occurs at $(0,1)$ and $(0,-1)$.
for i in range(len(s)):
print(f.subs(s[i]))
Minimize the volume of a rectangular prism subject to the suface area constraint $2yz+2xz+2xy=12$
x,y,z,h = symbols("x y z h")
A=2*y*z+2*x*z+2*x*y
V=x*y*z
ss=solve( [Eq(V.diff(x),h*diff(A,x)),
Eq(V.diff(y),h*diff(A,y)),
Eq(V.diff(z),h*diff(A,z)),
Eq(A,12)],
dict=True)
ss
Ignoring the solution with negative side lengths, we arrive at the minimum volume of the cube with sidelength $\sqrt{2}$:
V.subs(ss[1])
Minimize the surface area of a rectangular prism with fixed volume $V=xyz=1000$.
x,y,z,h = symbols("x y z h")
A=2*y*z+2*x*z+2*x*y
V=x*y*z
sss=solve( [Eq(V.diff(x),h*diff(A,x)),
Eq(V.diff(y),h*diff(A,y)),
Eq(V.diff(z),h*diff(A,z)),
Eq(V,1000)],
dict=True)
sss
Ignoring the complex solutions, we find the minimum surface area 600 occurs for the cube of sidelength 10
A.subs(sss[0])