# Summation of If statements

The following made me curious. Suppose you want to sum the if statement If[x[i] < 1., x[i]^2, 0.] over i=1,2, i.e.

Sum[If[x[i] < 1., x[i]^2, 0.], {i, 1, 2}].


Mathematica returns

If[x < 1., x[i]^2, 0.] + If[x < 1., x[i]^2, 0.].


Notice the i's if the statement is true. However, I thought a more "natural" representation of the sum should look like

If[x < 1., x^2, 0.] + If[x < 1., x^2, 0.].


Does anybody can enlighten me on this one? Thanks in advance.

• Try Sum[If[x[i] < 1., 1/0, 0^0], {i, 1, 2}]. – b.gates.you.know.what Feb 14 '13 at 10:11
• – Mr.Wizard Feb 22 '13 at 7:47

## 1 Answer

Since If has attribute HoldRest, the i will not be inserted into the latter parts during the evaluation. Consider this example showing the same effect:

Sum[s[i, Hold[i]], {i, 1, 2}]
(* s[1, Hold[i]] + s[2, Hold[i]] *)


I think the best practices way of getting what you are asking for is to use With to ensure i gets inserted:

Sum[With[{i = i}, If[x[i] < 1., x[i]^2, 0]], {i, 1, 2}]
(* If[x < 1., x^2, 0] + If[x < 1., x^2, 0] *)