# Writing a function that finds the difference between two maxima

Suppose i have two functions:

$\qquad -2x^2 +5x+3$

and

$\qquad -5x^2 +2x+3$

To solve the point where the functions are at maximum i use the command NMaximize which gives:

NMaximize[-2 x^2 + 5 x + 3, x]
(* Out: {6.125, {x -> 1.25}} *)


and

NMaximize[-5 x^2 + 2 x + 3, x]
(* Out: {3.2, {x -> 0.2}} *)


However, what if I want to define a function that automatically calculates the difference of the points $x_{max}$ of the two functions?

Now from the example I have given I want to define a function that will somehow automatically calculate $1.25-0.2=1.05$.

• Here is a very ugly approach: maxdiff[f1_, f2_] := NMaximize[f1, x][[2]][[1]][[2]] - NMaximize[f2, x][[2]][[1]][[2]] – Moo Mar 20 '16 at 5:50
• what does this part of the function mean: [[2]][[1]][[2]]? – PhilCsar Mar 20 '16 at 5:54
• [[...]] is shorthand for the Part command. Take a look at the documentation for Part and, more in general, at What the @#%^&*?! do all those funny signs mean?. – MarcoB Mar 20 '16 at 6:33

Since you are interested in the values of $x$ for which each function is maximized, NArgMax (docs) is more convenient than NMaximize in this case.

For instance:

Clear[f1, f2]
f1[x_] := -2 x^2 + 5 x + 3
f2[x_] := -5 x^2 + 2 x + 3

xdiff = NArgMax[f1[x], x] - NArgMax[f2[x], x]


Note that the two maxima correspond to $x=1.25$ and $x=0.2$ as you said, so the difference is actually $1.05$, not $1.23$.

If you'd like to package this into a function, you could do that in many ways of course. Here's one:

Clear[xdiff]
xdiff[first_, second_] := Subtract @@ (NArgMax[#[x], x] & /@ {first, second})


Using the f1 and f2 I defined above, you could evaluate:

xdiff[f1, f2]

(* Out: 1.05 *)