Using Summations Instead of Loops

For certain calculations that involve summations, you can use the Σ function instead of loops. You can use Σ with stack syntax or with algebraic syntax. Σ automatically repeats the addition for the specified range of the index variable — without using a loop structure.

Example: The following programs take an integer upper limit n from the stack, then find the summation. One program uses a FOR … NEXT loop — the other uses Σ.

n

j2

 

 

Program:

Comments:

j = 1

 

 

 

 

«

 

 

0 1 ROT

Initializes the summation and puts

 

 

the limits in place.

 

FOR j

Loops through the calculation.

 

j SQ +

 

 

NEXT

 

 

»

 

 

 

 

Program:

Comments:

 

 

«

 

→ n

Uses Σ to calculate the summation.

'Σ(j=1,n,j^2)'

 

»

 

 

 

Example: The following program uses ΣLIST to calculate the summation of all elements of a vector or matrix. The program takes from the stack an array or a name that evaluates to an array, and returns the summation.

Program:

Comments:

 

 

«

 

OBJ→

Finds the dimensions of the array and

 

leaves it in a list on level 1.

1

Adds 1 to the list. (If the array is a vector,

+

the list on level 1 has only one element.

 

ΠLIST will error if the list has fewer than

 

two elements.)

œLIST

Multiplies all of the list elements together.

→LIST

Converts the array elements into a list, and

ΣLIST

sums them.

»

 

 

 

1-26 RPL Programming