3

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] < 1., x[i]^2, 0.] + If[x[2] < 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] < 1., x[1]^2, 0.] + If[x[2] < 1., x[2]^2, 0.].

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

dionys
  • 4,321
  • 1
  • 19
  • 46
chris
  • 395
  • 1
  • 8

1 Answers1

9

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] < 1., x[1]^2, 0] + If[x[2] < 1., x[2]^2, 0] *)
jVincent
  • 14,766
  • 1
  • 42
  • 74