3
$\begingroup$

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.

$\endgroup$
2
9
$\begingroup$

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] *)
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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