Message Boards Message Boards

6 Replies
3 Total Likes
View groups...
Share this post:

How To Add Functions?

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.

POSTED BY: Frank Kampas
6 Replies

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]
POSTED BY: liginity lee

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
POSTED BY: Frank Kampas

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.

POSTED BY: Frank Kampas

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]
POSTED BY: Frank Kampas

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]
POSTED BY: Frank Kampas

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
POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract