Mathematica's evaluation of nested summations

106 Views Asked by At

Suppose we want to count the number of instructions executed by the following Python code:

sum = 1
print("1 instruction first")

for i in range(1,n+1):
    for j in range(i,n-3+1):
        sum = sum + i + j 
        print(f"3 instructions here : {i}, {j}")

Trivially, for n = 5 (for example), we can count 10 instructions (1 instruction for the first line, and 3 instructions to compute the sum):

1 instruction first
3 instructions here : 1, 1
3 instructions here : 1, 2
3 instructions here : 2, 2

Let us try to evaluate this mathematically. The number of instructions is given by the following expression:

$$ 1 + \sum_{i=1}^{n} \sum_{j=i}^{n-3} 3 $$

Mathematica evaluates this expression as $\frac{3}{2} (n - 5) n + 1$... which is equal to $1$ for $n=5$. Indeed this closed formula doesn't take into account the fact that by convention, an empty sum (when the start index of the variable is greater than the upper bound) sums to 0.

So, three questions:

  1. did I make a mistake in my reasoning?
  2. is there a bug in Mathematica (I mean, with respect to what I exposed there)?
  3. how to correctly express the for loops with sums in that case?
1

There are 1 best solutions below

0
On

One thing you could have done is to re-express your sum. I like using Iversonian machinery for such things, and I shall employ that here.

Starting with

$$1 + \sum_{i=1}^{n} \sum_{j=i}^{n-3} 3$$

one way of evaluating this sum is to evaluate the inner sum first:

$$1 + \sum_{i=1}^{n} 3(n-i-2)$$

which is exactly what leads to the expression giving faulty results. If instead, you do the following:

$$\begin{align*} 1 + \sum_{i=1}^{n} \sum_{j=i}^{n-3} 3&=1+\sum\sum3[1\le i \le n][i\le j\le n-3]\\ &=1+\sum\sum3[1\le i\le j\le n-3 < n]\\ &=1+\sum\sum3[1\le j\le n-3][1\le i\le j]\\ &=1+\sum_{j=1}^{n-3}\sum_{i=1}^j 3\\ &=1+\sum_{j=1}^{n-3}3j=1+\frac32(n-2)(n-3)\\ \end{align*}$$

you get an expression that (mostly) works in Alpha, where everything is as expected except at $n=1$.

(answering here instead of mathematica.SE, since it should have been addressed here, and that other site does not really entertain Alpha questions)