Trabb Pardo–Knuth algorithm

From HandWiki

Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages. In their 1977 work "The Early Development of Programming Languages", Trabb Pardo and Knuth introduced a small program that involved arrays, indexing, mathematical functions, subroutines, I/O, conditionals and iteration. They then wrote implementations of the algorithm in several early programming languages to show how such concepts were expressed.

The trivial Hello world program has been used for much the same purpose.

The algorithm

ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
    call a function to do an operation
    if result overflows
        alert user
    else
        print result

The algorithm reads eleven numbers from an input device, stores them in an array, and then processes them in reverse order, applying a user-defined function to each value and reporting either the value of the function or a message to the effect that the value has exceeded some threshold.

ALGOL 60 implementation

begin integer i; real y; real array a[0:10];
   real procedure f(t); real t; value t;
      f := sqrt(abs(t)) + 5 * t ^ 3;
   for i := 0 step 1 until 10 do read(a[i]);
   for i := 10 step -1 until 0 do
   begin y := f(a[i]);
      if y > 400 then write(i, "TOO LARGE")
                 else write(i, y);
   end
end.

The problem with the usually specified function is that the term 5 * t ^ 3 gives overflows in almost all languages for very large negative values.

C implementation

This shows a C implementation equivalent to the above ALGOL 60.

#include <math.h>
#include <stdio.h>

double f(double t)
{
    return sqrt(fabs(t)) + 5 * pow(t, 3);
}

int main(void)
{
    double a[11], y;
    int i;

    for (i = 0; i < 11; i++)
        scanf("%lf", &a[i]);

    for (i = 10; i >= 0; i--) {
        y = f(a[i]);
        y > 400 ? puts("TOO LARGE") : printf("%lf\n", y);
    }

    return 0;
}

Python implementation

This shows a Python implementation which works with either version 2 or version 3.

import math

f = lambda t: math.sqrt(abs(t)) + 5 * t ** 3
a = [float(input()) for _ in range(11)]

for t in reversed(a):
    y = f(t)
    print('TOO LARGE' if y > 400 else y)

References

  • "The Early Development of Programming Languages" in A History of Computing in the Twentieth Century, New York, Academic Press, 1980. ISBN:0-12-491650-3 (Reprinted in Knuth, Donald E., et al., Selected Papers on Computer Languages, Stanford, CA, CSLI, 2003. ISBN:1-57586-382-0) (typewritten draft, August 1976)

External links