Is summation the equivalent of a for loop? (Programming)

4.9k Views Asked by At

It says here that summation is in this form. It got me thinking for those of you who know programming, isn't this basically the same as a for loop to some extent? Since i is some sort of a variable (index which is incremented by one every time) holding m whilst n is where the incrementation stops when i = n. An example of how this would be in PHP:

<?php 
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
} 
?>

\$x being our i in this case and 10 being n while the $x++ is the incrementation that in our case; i does until it is the same value as n.

2

There are 2 best solutions below

2
On BEST ANSWER

Yes! Both summations and for loops are designed as a shorthand of saying "I want to do this a whole bunch of times but I don't really want to write it all out. Here's the step to repeat and the pattern each step varies by, have at it ;) ."

I could define some variable x = 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100, or I could just say x = [the sum of the squared integers 1 to 10, inclusive]. As you pointed out, this is just a summation: sigma from i=1 to 10 of i^2; if you were to ask a computer scientist to add those numbers together, immediatly (s)he would type something like this:

int x = 0;
for(int i = 1; i <= 10; i++) {
    x += i*i;
}

As I'm sure you recognize, this is a rather trivial example. The power of a for loop comes not from adding a bunch of numbers but from executing statements of code with the altered variable as a parameter. Whereas sigma can be thought of as a function that sums the results of some function (as it really is, in its most general form, sigma from i=[lower bound] to [upper bound] of f(i), where f(x) is some function... sorry about the formating, I'm not sure how to do mathematic symbols on SE), a for loop can perform actions with those values of f(i).

I'm not sure if that makes sense, but I guess the TL;DR summery would be that yes, a summation is just a specific kind of for-loop, but a for-loop is much more expressive as it allows the programmer to define what to do with the values of its incrementing variable(s). I suppose you could say there's greater logical control in a for-loop than you find in a summation.

1
On

$\sum_{n=a}^b f(n)$

is equivalent to

<?php 
$sum = 0;
for ($n = a; $n <= b; $n++) {
  sum +=f(n);
} 
?>

Or in Python, sum([f(n) for n in range(a,b+1)])