fkampas
(Frank Kampas)
May 15, 2015, 5:35pm
1
Mathematica does not add functions directly.
In[1]:= cs = Cos + Sin;
In[2]:= cs[1]
Out[2]= (Cos + Sin)[1]
You can use Through
In[3]:= cssum = Through[(Cos + Sin)[#]] &
Out[3]= Through[(Cos + Sin)[#1]] &
In[4]:= cssum[1]
Out[4]= Cos[1] + Sin[1]
However, what I want to do is convert Cos + Sin to
In[5]:= cssum1 = (Cos[#] + Sin[#]) &;
In[6]:= cssum[1]
Out[6]= Cos[1] + Sin[1]
I haven’t figured out how to do that.
dreiss
(David Reiss)
May 15, 2015, 6:56pm
2
Something along these lines might work…
In[1]:= cssum =
Module[{x, temp, head},
temp = head[x, #[x] & /@ (Cos + Sin)];
temp /. head -> Function
]
Out[1]= Function[x$24156, Cos[x$24156] + Sin[x$24156]]
In[2]:= cssum[\[Pi]]
Out[2]= -1
fkampas
(Frank Kampas)
May 15, 2015, 7:38pm
3
That seems promising. I wrote a function based on your idea:
In[20]:= funcAdd[funcs_List] :=
Block[{temp, head},
temp = head[x, #[x] & /@ Plus @@ funcs];
Function @@ temp]
In[22]:= csf = funcAdd[{Cos, Sin}]
Out[22]= Function[x, Cos[x] + Sin[x]]
In[23]:= csf[1]
Out[23]= Cos[1] + Sin[1]
In[25]:= t = funcAdd[{#.# &, #.#/Sqrt[#.#] &}]
Out[25]= Function[x, Sqrt[x.x] + x.x]
In[26]:= t[Range[4]]
Out[26]= 30 + Sqrt[30]
fkampas
(Frank Kampas)
May 15, 2015, 7:57pm
4
Actually, the approach can be made more general.
In[33]:= funcCombine[funcs_List, op_] :=
Function[x, Evaluate[#[x] & /@ op @@ funcs]]
In[35]:= cs3 = funcCombine[{Cos, Sin}, Plus]
Out[35]= Function[x$, Cos[x$] + Sin[x$]]
In[36]:= cs3[1]
Out[36]= Cos[1] + Sin[1]
In[37]:= cs4 = funcCombine[{Cos, Sin}, Times]
Out[37]= Function[x$, Cos[x$] Sin[x$]]
In[38]:= cs4[1]
Out[38]= Cos[1] Sin[1]
fkampas
(Frank Kampas)
May 16, 2015, 1:21pm
5
The method needs more work for combining functions that contain derivatives.
In[1]:= funcCombine[funcs_List, op_] :=
Function[x, Evaluate[#[x] & /@ op @@ funcs]]
In[9]:= d1 = funcCombine[{D[#, x] &, D[#, y] &}, Plus]
Out[9]= Function[x$, 0]
I can combine total derivatives
In[10]:= d2 = funcCombine[{Dt[#, x] &, Dt[#, y] &}, Plus]
Out[10]= Function[x$, Dt[x$, x] + Dt[x$, y]]
In[11]:= d2[x y]
Out[11]= x + y + y Dt[x, y] + x Dt[y, x]
but that leaves me stuck with Dt, not D.
fkampas
(Frank Kampas)
May 16, 2015, 1:25pm
6
This works, but there may be a better approach
In[13]:= d3 =
funcCombine[{Dt[#, x, Constants -> {y}] &,
Dt[#, y, Constants -> {x}] &}, Plus]
Out[13]= Function[x$,
Dt[x$, x, Constants -> {y}] + Dt[x$, y, Constants -> {x}]]
In[14]:= d3[ x y ]
Out[14]= x + y
I would like to post a simple solution for addition of functions, probably understandable to most of mma users. Evaluate[ ] would calculate the result.
In[1]:= cs[x_] := Evaluate[Cos[x] + Sin[x]]
In[2]:= cs[x]
Out[2]= Cos[x] + Sin[x]