8

I want to create the functions $even[f]$ and $odd[f]$ which will apply the formula $even[f(x)] = \frac{f(x)+f(-x)}{2}$ and $odd[f(x)]=\frac{f(x)-f(-x)}{2}$ for an arbitrary $f$.

I tried using

even[ff, x_] := (ff[x] + ff[-x])/2

But that doesn't seem to work. What would the correct approach to this be?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
R R
  • 225
  • 2
  • 4
  • even[f_[x_]] := (f[x] + f[-x])/2 and odd[f_[x_]] := (f[x] - f[-x])/2 – RunnyKine Feb 18 '14 at 04:38
  • 1
    or like this: `even[f_] := (f[#] + f[-#])/2 &;
    odd[f_] := (f[#] - f[-#])/2 &`
    
    – Szabolcs Feb 18 '14 at 04:39
  • Neither approach is working for me at the moment. In the first approach mathematica doesn't evaluate anything, just leaving the even function with whatever its argument is, and in the second approach I have a lot of #'s that are left unevaluated as well. – R R Feb 18 '14 at 04:46
  • When I boot mathematica fresh and enter it in this is what I get:In[28]:= ClearAll[f, ff, even, x]

    In[29]:= even[f_[x_]] := (f[x] + f[-x])/2

    In[30]:= f[x_] := x^2 + x

    In[35]:= even[f] even[f[x]] even[f[x_]] even[f[#]]

    Out[35]= even[f]

    Out[36]= even[x + x^2]

    Out[37]= even[x_ + x_^2]

    Out[38]= even[#1 + #1^2]

    – R R Feb 18 '14 at 05:12
  • When I type in manually, (f[x]+f[-x])/2 it produces x^2, which is what I want it to do. How do I make my manual typing in into something that isn't manual? I want to automate that. – R R Feb 18 '14 at 05:14
  • I still have the same issue. I am running v.9 the student edition, would that a play a role at all? – R R Feb 18 '14 at 05:23
  • 1
    Did you SetAttributes like I did? – RunnyKine Feb 18 '14 at 05:23
  • I didn't notice that until now, sorry. Now when it works when I do it on a defined function. What is HoldAll doing in this context? – R R Feb 18 '14 at 05:27

2 Answers2

17
SetAttributes[{even, odd}, HoldAll];
even[f_[x_]] := (f[x] + f[-x])/2;
odd[f_[x_]] := (f[x] - f[-x])/2;

Usage

g[x_] := x + x^2;

even[g[x]]

x^2

OR as Szabolcs suggested using pure functions:

even[f_] := (f[#] + f[-#])/2 &;
odd[f_] := (f[#] - f[-#])/2 &

Usage

Using the same g as above

even[g][x]

x^2

RunnyKine
  • 33,088
  • 3
  • 109
  • 176
  • 4
    It might be helpful to mention that Szabolcs' method requires calling even[g][x] instead of even[g[x]]. Also it doesn't require HoldAll. –  Feb 18 '14 at 10:19
7

You said you tried using

even[ff, x_] := (ff[x] + ff[-x])/2

but I guess you forgot to put the underscore on the first argument. If you do

even[ff_, x_] := (ff[x] + ff[-x])/2

instead, then it works.

g[x_] := x + x^2;
even[g, x]

x^2

P.S. No SetAttributes necessary using this method.