4

Mathematica has a symbolic solver for quadratic (and maybe other) functions, e.g.:

Minimize[2 x^2 - y x + 5, {x}]

will yield the following solution:

{1/8 (40-y^2),{x->y/4}}

Is this feature supported in SymPy or a derivative library? Or I have to implement it myself?

Thanks a lot for your opinion!

tribbloid
  • 4,026
  • 14
  • 64
  • 103
  • There isn't one; one has to write some code using `diff`, `solve` (or `solveset`), and worry about endpoints / behavior at infinity, or use second derivative test, etc. –  Jun 25 '18 at 02:50

1 Answers1

0

I'm not sure about the generality of this approach, but the following code:

import sympy
from sympy.solvers import solve

x = sympy.var('x')
y = sympy.var('y')

f = 2*x**2 - y*x + 5

r = solve(f.diff(x), x)
f = f.subs(x, r[0])

print(f)    
print(r)

Outputs:

-y**2/8 + 5
[y/4]

The first line of output (-y**2/8 + 5) is equivalent to Mathematica's 1/8 (40-y^2), just ordered differently.

The second line ([y/4]) is similar to Mathematica's {x->y/4} (solve returns a list of roots)

The idea is that we first take the partial derivative of f with respect to x, then substitute it into the original function.

jedwards
  • 29,432
  • 3
  • 65
  • 92
  • 2
    The generality of this approach is limited, for example if the function was `-(2*x**2 - y*x + 5)`, then it would give the same `y/4` even though it's now the maximum instead of minimum. There may be multiple zeros of the derivative, and one has to compare the values of f at each of them to the limits of f as x->infinity or negative infinity (the latter can be found with SymPy, too). –  Jun 25 '18 at 04:18