4
$\begingroup$

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$.

$\endgroup$
3
  • $\begingroup$ Here is a very ugly approach: maxdiff[f1_, f2_] := NMaximize[f1, x][[2]][[1]][[2]] - NMaximize[f2, x][[2]][[1]][[2]] $\endgroup$
    – Moo
    Commented Mar 20, 2016 at 5:50
  • $\begingroup$ what does this part of the function mean: [[2]][[1]][[2]]? $\endgroup$
    – anonymous
    Commented Mar 20, 2016 at 5:54
  • 1
    $\begingroup$ [[...]] 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?. $\endgroup$
    – MarcoB
    Commented Mar 20, 2016 at 6:33

1 Answer 1

9
$\begingroup$

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 *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.