8
$\begingroup$

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?

$\endgroup$
9
  • $\begingroup$ even[f_[x_]] := (f[x] + f[-x])/2 and odd[f_[x_]] := (f[x] - f[-x])/2 $\endgroup$
    – RunnyKine
    Feb 18, 2014 at 4:38
  • 1
    $\begingroup$ or like this: even[f_] := (f[#] + f[-#])/2 &; odd[f_] := (f[#] - f[-#])/2 & $\endgroup$
    – Szabolcs
    Feb 18, 2014 at 4:39
  • $\begingroup$ 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. $\endgroup$
    – R R
    Feb 18, 2014 at 4:46
  • $\begingroup$ 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] $\endgroup$
    – R R
    Feb 18, 2014 at 5:12
  • 1
    $\begingroup$ Did you SetAttributes like I did? $\endgroup$
    – RunnyKine
    Feb 18, 2014 at 5:23

2 Answers 2

17
$\begingroup$
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

$\endgroup$
1
  • 4
    $\begingroup$ 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. $\endgroup$
    – user484
    Feb 18, 2014 at 10:19
7
$\begingroup$

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.

$\endgroup$
0

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.