Spreadsheet Factorials
Spreadsheets can be used for programming computations. Without scripts or macros a spreadsheet does not have a loop capability. But, it can perform computations referencing cells to provide a sequence of cells with factorials. Cells are much like variables in other programming languages, they store values.The figure below shows a spreadsheet programmed to compute the factorials from 1 to 30. In column A is the number which increases from 1 to 30. In column B is an equation to calculate the next factorial. Column C shows the equation that is in column B. And column D has the result of the spreadsheet function fact().
Entering the equations and numbers could be quite tedious. Nothing should be tedious on a computer. All spreadsheets have methods for entering such sequences of equations and numbers. Note the selected cell, C2, with the outline and small square in the lower right corner. To enter the sequence of numbers in column A, enter 1 in cell A2 and 2 in cell A3, then select both cells, pause then drag the small square in the corner down to cell A31. Enter "1" in cell B2 and "=A3*B2" in cell B3. In cell C3 enter "=formula(B3)", in cell D2 enter "=fact(A2)" and finally in cell D3 put "=fact(A3)". Exclude the quotation marks in all cell entries. Then to fill in the remaining cells, select cells B3 to D3, then drag the small corner square down to cell D31.
This is from the spreadsheet program "LibreOffice" version 3.6. If the columns are expanded additional zeros will fill the column. However, 21! and further are not exact. 21! equals 51090942171709440000 not 51090942171709400000 this indicates that double precision (8 byte) floats are use in computations. Other spreadsheets, "Calligra Sheets" and "gnumeric" get 21! correct but have errors on 22!.
It is possible to have loops in scripts or macros which are programs that run inside the spreadsheet. The following is a macro function in Star Basic (this should work in MS basic macro also). After compiling this macro enter "=factorial( ... )" in a cell to obtain the factorial. Do not enter the quotation marks and "..." can be a cell reference or a number.
1: Function factorial ( n as Long ) as Double
2: k = 1
3: for i = 1 to n
4: k = k * i
5: next i
6: factorial = k
7: end Function
Line-by-line description
- Start of the function with an argument (or parameter) of "n" that is a long (4 byte integer) with a return value that is a Double ( 8 byte float).
- Initialize k to one. If not initialized k would be zero so the result would be zero.
- Begin a loop with index "i" that ends on line 5.
- Computation of factorial, setting k = k times i for each i.
- Use the next i value and go to the start of the loop, line 3.
- The value returned from the function is the same name as the function within the function.
- The end of the function.
No comments:
Post a Comment