I need to evaluate an expression, sum in this case, involving an arbitrary function. Below is a simplified version of what I wanted to do:

points = {1.3, 2.4};
f1[g_] = g^2 + 1;
f2[g_] = Sum[f1[g[points[[i]]]], {i, 2}];

I want to be general so g is an arbitrary function. It works for simple functions, for example, if I want g[x]=Sin[x], then


gives the correct answer 3.38469. My problem is, in the actual code, g is much more complicated. A simpler example will suffice. If I want g[x]=Sin[x]+Cos[x], then the following does not work:

f2[Sin +Cos]

Will be glad if someone can help or give a useful hint. Thank you in advance!


2 Answers 2


First recommendation: use := to define your functions.

f1[g_] := g^2 + 1
f2[g_] := Sum[f1[g[points[[i]]]], {i, 2}]

This guarantees that g will be interpreted as the name of the argument pattern, rather than first evaluated as a global symbol.

Now, note that Sin+Cos isn't a function, it's just the sum of the symbols Sin and Cos, usually meaningless. Define a function:

h[x_] := Sin[x] + Cos[x]

Now, it's all fine:

(* 3.51934 *)

But now, a further recommendation: don't use Sum to add things. Sum is a tool of analysis, a way to figure out things like infinite sums. Better, and easier, to use Total:

f3[g_] := Total[f1[g /@ points]]
(* 3.51934 *)

Here, I map g to the points (/@), and take advantage of the fact that your f1 is implicitly Listable to further simplify. An advantage of Total here is that it just adds all your points, regardless of how many there are. You need not keep track. Another advantage, when you have many points, is that it's less subject to roundoff error than simply adding the points in order.


f1[x_] := x^2 + 1;

Using Composition ( @* ) and restricting the argument of f2 to expressions with the Head of Function and operating on a vector of variable length (length 2 in your example),

f2[g_Function] := Total[f1@*g /@ points]

Format[pt[n_]] := Subscript[pt, n]

n = 5;

points = Array[pt, n];

f2[g[#] &]

enter image description here

f2[Sin[#] &]

enter image description here

f2[Sin[#] + Cos[#] &] // Simplify

enter image description here


Not the answer you're looking for? Browse other questions tagged or ask your own question.