I want to compute a double sum like below with i != j. (When i =j, the denominator will be zero, which can not be assessed). Does anyone know how to do it? I want to skip the calculation when i=j.


I found a appraoch like this:

pairs = Subsets[Range[10], {2}];
test[{i_, j_}] := 1/(i - j);
Total[test /@ datas]*2

which gives a result of -(4861/126), which is the anwser I need. But this method requires more time than the Sum funciton in Mathematica. (In addition, my function is more complex than the 1/i-j.

I would like to bid my sincere appreciate to any help.

  • $\begingroup$ 2 Sum[1/(i - j), {i, 1, 10}, {j, 1, i - 1}] $\endgroup$
    – Natas
    Aug 29, 2020 at 10:51

2 Answers 2

m = SparseArray[{{i_, j_} /; j > i -> 1/(i - j)}, {10, 10}];

Just because of its symmetry your sum is equal to zero. If you need sometjing else, where you need to exclude the case i=j under the sum, you may do as follows:

Sum[If[i != j, 1/(1 + (i - j)^2), 0], {i, 1, 3}, {j, 1, 3}]

(* 12/5 *)

Have fun!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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