Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition of Functions

So generally, if you have two functions f,g: X -->Y, and if there is some binary operation + defined on Y, then f + g has a canonical definition as the function x --> f(x) + g(x).

What's the best way to implement this in Mathematica?

f[x_] := x^2
g[x_] := 2*x
h = f + g;
h[1]

yields

(f + g)[1]

as an output

of course,

H = Function[z, f[z] + g[z]];
H[1]

Yields '3'.

like image 249
nick maxwell Avatar asked Oct 25 '11 22:10

nick maxwell


People also ask

What is addition and subtraction of operation of function?

To add or subtract functions, just add or subtract the values at each point where it makes sense. If the functions are given by formulas, you can just add or subtract the formulas (it doesn't matter whether you plug in values before or after).


2 Answers

Consider:

In[1]:= Through[(f + g)[1]]

Out[1]= f[1] + g[1]

To elaborate, you can define h like this:

h = Through[ (f + g)[#] ] &;

If you have a limited number of functions and operands, then UpSet as recommended by yoda is surely syntactically cleaner. However, Through is more general. Without any new definitions involving Times or h, one can easily do:

i = Through[ (h * f * g)[#] ] &
i[7]
43218
like image 136
Mr.Wizard Avatar answered Oct 20 '22 12:10

Mr.Wizard


Another way of doing what you're trying to do is using UpSetDelayed.

f[x_] := x^2;
g[x_] := 2*x;

f + g ^:= f[#] + g[#] &; (*define upvalues for the operation f+g*)

h[x_] = f + g;

h[z]

Out[1]= 2 z + z^2

Also see this very nice answer by rcollyer (and also the ones by Leonid & Verbeia) for more on UpValues and when to use them

like image 27
abcd Avatar answered Oct 20 '22 12:10

abcd