I'd like a simple interface where the user can input (by text) a function $f(x)$, and then the function, its even part, and its odd part are all plotted on the same axes. I'd also like PlotLegend to show the mathematical form of $f(x)$, as well as the even and the odd functions.

Recall that $f_e = \frac{f(x) + f(-x)}{2}$ and $f_o = \frac{f(x) - f(-x)}{2}$. So for instance if the user puts in Sin[x] + 3 Cos[x] + x^2, I'd like the following three graphs plotted:

  • Sin[x] + 3 Cos[x] + x^2
  • 3 Cos[x] + x^2
  • Sin[x]

I'd also like the PlotLegends to be

  • $f(x) = \sin x + 3 \cos x + x^2$
  • $f_e (x) = 3 \cos x + x^2$
  • $f_o (x) = \sin x$

Here is a weak start:

Panel[DynamicModule[{f = Sin[x] + 2 Cos[x] + x^2},
    Dynamic[Plot[{f, f/2, f/3}, {x, -5, 5},
      ImageSize -> 300,
      PlotLegends -> {"f = " f, 
        "\!\(\*SubscriptBox[\(f\), \(e\)]\) = " f/2, 
        "\!\(\*SubscriptBox[\(f\), \(o\)]\) = " f/4}]]}]]]

Note that this does not compute the even and the odd parts.

I cannot get the plot legends to be properly typeset either. For instance there are spurious and unnecessary parentheses around entire expression; the equations are sometimes mangled by being "factored," and so on.

Finally, I want each time the user types a new equation into the InputField, the previous graph disappears. That is, I don't want the user to use this code 10 times with different equations and get a set of 10 graphs remaining; only the most recent graph should remain.


1 Answer 1

evenPart = Simplify@(# + (# /. #2 -> -#2))/2 &;

oddPart = Simplify@(# - (# /. #2 -> -#2))/2 &;

Panel[DynamicModule[{f = Sin[x] + 2 Cos[x] + x^2}, 
    Dynamic[Plot[Evaluate@{f, evenPart[f, x], oddPart[f, x]}, 
      {x, -5, 5}, 
      ImageSize -> 300, 
      PlotLegends -> {Row[{Style["f ", Italic], " = ", f}], 
        Row[{Subscript[Style["f ", Italic], e], " = ", evenPart[f, x]}], 
        Row[{Subscript[Style["f ", Italic], o], " = ", oddPart[f, x]}]}]]}]]]

enter image description here

enter image description here

  • $\begingroup$ Excellent... almost... ($+1$) The last request stated was that multiple uses of the code do not lead to a long string of plots. Only the last plot should be visible at any time. Does this mean the code should be a Manipulate? $\endgroup$ Commented Jun 6, 2023 at 0:22
  • 1
    $\begingroup$ David, if you use Return after entering your input in the input field (instead of Shift+Return) the changes in plot will be in-place, so the code will not produce a string of plots. $\endgroup$
    – kglr
    Commented Jun 6, 2023 at 0:26
  • $\begingroup$ Oh gee... how did I not know that? Thanks as always. ($\checkmark$) $\endgroup$ Commented Jun 6, 2023 at 0:29

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.