Scripting · small reusable functions
Scripting Numerical Functions
A script is a plain text file of statements that a numerical environment runs in order, and a script function is a named block inside one that takes arguments and returns a result. Writing the numerical parts of a task as functions, instead of as one long run of statements, makes each part testable, reusable and easy to read. The same advice holds for any matrix-oriented scripting language, so the examples here use short generic pseudocode.
The approach below is built around four habits: decide the signature, check the inputs, compute with whole-array operations, and test against answers known in advance. Two small functions illustrate it, the running quotient and the Fibonacci numbers, both of which have exact results to compare against.
Start from the signature
Before writing any statement, fix what goes in and what comes out. A function that computes the running quotient of a sequence takes one vector and returns a vector one element shorter. A function that returns the first n Fibonacci numbers takes a non-negative integer and returns a vector of length n. Writing this down in a comment line first catches design problems early: if the output length depends on the data in a way that surprises the caller, the signature needs another look.
Names should say what the function computes, and arguments should be in the order a reader expects, data first and options after. Optional arguments with defaults, such as a tolerance, belong at the end.
Check the inputs
A numerical function fails in confusing ways when given bad data, so it pays to reject the bad cases at the top. Check that the input has the right shape, that counts are integers, that sizes are not negative, and that values that will be divided by are not zero. An error message should name the argument and the rule it broke.
The cost of a few comparisons is negligible next to the cost of a wrong answer that looks plausible. The one exception is a function called millions of times inside a loop, where the checks can move to the caller.
Compute with whole arrays
Matrix-oriented languages apply an operation to every element of a vector at once, which is both shorter and faster than an explicit loop. The running quotient shows this well. With a vector x of length n, the quotients are the elements 2 to n divided by the elements 1 to n − 1:
function r = runquot(x)
check that x is a vector with at least two elements
check that x(1 : n−1) contains no zero
r = x(2 : n) ./ x(1 : n−1)
end
For x = 1, 1, 2, 3, 5, 8 the result is 1, 2, 1.5, 1.6667, 1.6, a vector of five elements, as the signature promised. The element-wise division operator works like its multiplication counterpart.
Loops remain the right tool when each step depends on the previous result, as in a recurrence. The Fibonacci numbers are the standard case:
function f = fibo(n)
check that n is an integer ≥ 1
f = zeros(1, n); f(1) = 1
if n ≥ 2: f(2) = 1
for k = 3 : n: f(k) = f(k−1) + f(k−2)
end
Preallocating the output, as in the first line of the body, avoids growing a vector one element at a time, which copies the data repeatedly. The numbers and their limits in double precision are discussed on the Fibonacci numbers page.
Test against known answers
Every function should come with a few checks whose results are known without running it. For runquot, a geometric sequence 2, 6, 18, 54 must give 3, 3, 3. For fibo, fibo(10) must end in 55 and fibo(20) in 6765. Identities help too: the quotients of the Fibonacci vector approach 1.618034, and a cumulative product of the running quotient, multiplied by the first element, must reproduce the original sequence.
Floating-point results are compared with a tolerance, not with exact equality. A relative tolerance of 10⁻¹⁰ is a typical choice for results that involve a few dozen operations, tighter for plain arithmetic and looser for iterative methods. Integer-valued results are compared exactly, which is why the limit where doubles stop holding integers exactly matters for the Fibonacci example.
Keep functions small
A function that does one thing is easy to test, and it can be combined with others. If a task needs both a sequence and its running quotient, call two functions rather than building a third that does both. When a function grows past a screenful, look for a piece that can be named and moved out.
Document the function in the first comment lines: one sentence on what it computes, then the arguments and the result, then a note on what happens in edge cases. That text is what the next reader sees first.
Where this leads
The same structure carries over to heavier numerical work. A function that evaluates an expansion by Lentz’s method follows the same four steps, with a tolerance argument and an error return for non-convergence. A function that looks up values in a table is a case of one-dimensional interpolation. Neighboring methods and further examples are gathered under interpolation and calculus.