4

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

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
anonymous
  • 433
  • 3
  • 9

1 Answers1

9

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 *)
MarcoB
  • 67,153
  • 18
  • 91
  • 189