Having an exact input we can find an exact solution:
Maximize[{ 5 x^2 + x + 2, -5 <= x <= 5}, x]
{132, {x -> 5}}
We could simply provide appropriate mathematical tools fulfilling expectations (adequate conditions on derivatives of the function, i.e. vanishing of the first derivative (a critical point) and negativity of the second derivative, then also inspecting boundary values) but with Maximize
the task is simplified.
Warning:
Maximize
(respectively Minimize
) yielding appropriate extremal values of the function can omit some arguments where it has extremal values. This problem can be resolved using Lagrange multipliers (see e.g. How can I implement the method of Langrange multipliers to find constrained extrema?) or solving directly adequate equations.
Example 1
Maximize[{5 x^2 + x + 2, -(26/5) <= x <= 5}, x]
{132, {x -> -(26/5)}}
but recalling the first example we would expect: {132, {x -> -(26/5)}, {x -> 5}}
.
To remedy this problem we could do:
Solve[{#1 == First[ Maximize[{#1, #2}, x]], #2}, x]& @@ { 5 x^2 + x + 2,
-(26/5) <= x <= 5 }
{{x -> -(26/5)}, {x -> 5}}
Example 2
Maximize[{x^4 - 3 x^2 - 1, -Sqrt[3] <= x <= Sqrt[3]}, x]
{-1, {x -> 0}}
Here boundary arguments were omitted, but solving this system we can get all solutions
Union @
Solve[{#1 == First[ Maximize[{#1, #2}, x]], #2}, x]& @@ { x^4 - 3 x^2 - 1,
-Sqrt[3] <= x <= Sqrt[3]}
{{x -> 0}, {x -> -Sqrt[3]}, {x -> Sqrt[3]}}
Plot[ x^4 - 3 x^2 - 1, {x, -2, 2}, PlotStyle -> Thick,
Epilog -> {Darker @ Green, Thick, Line[{{-Sqrt[3], -1}, {Sqrt[3], -1}}]}]
Similar problems we can encounter in more dimensional spaces and higher order equations.
x=xLower
,x=xUpper
, and (as @ssch observed), `x=-b/(2*a). Pick the largest of the corresponding y values. $\endgroup$