To find x
that maximises (c + x) / 2
subject to 0 <= x <= c <= 1
is mathematically trivial: the solution is x = c
, whatever the value of c
.
How does one express that in Python?
- I can solve equations with inequality constraints e.g. using
scipy.optimize.linprog
, but I have difficulty to understand how I can formulate the problem in such a way that the answer will bex = c
whenc
has no fixed numeric value. - Perhaps a symbolic toolbox such as
sympy
is suited for the task, but, again, how do I formulate this?
The above is a simple example equation. I have many of such equations like 1 - (x + c) / 2
and so on. They are all linear. There are also equations with more unknown values such as c1
and c2
. I can formulate them easily, but the question is the same every time: How do I let Python solve (maximise/minimise) such equations?
Try 1, scipy.optimize.linprog
:
from scipy.optimize import linprog
f = [-.5, -.5, 0] # columns: c, x, 1
A_ub = [[0,-1,0], [-1,1,0], [1,0,-1]]
b_ub = [0, 0, 0]
bounds = ((0, 1), (0, 1), (1, 1))
res = linprog(f, A_ub, b_ub, bounds=bounds)
How does the value of res.x
(which is [1., 1., 1.]
) imply x = c
?
Try 2, sympy
from sympy import symbols, solve, Max
x, c = symbols('x,c')
exp = (c + x) / 2
res = solve([Max(exp), 0 <= x, x <= c, c <= 1], x)
The answer is: (0 <= x) & (c <= 1) & (x <= c) & (-oo < c) & (-oo < x) & (x < oo) & Eq(x, -c)
which raises more questions than it answers.