这篇文章不是关于学习一些新的复杂算法,而是关于编程的历史。引入 TPK 是为了说明计算机编程语言的演变。当您完成本文时,您将学到一些关于编程历史的知识,而不是一个新概念。
在他们 1977 年的著作“编程语言的早期发展”中,Trabb Pardo 和 Knuth 介绍了一个涉及数组、索引、数学函数、子例程、I/O、条件和迭代的小程序。这个程序是用几种早期的编程语言编写的,以展示编程语言的演变。
就像“你好世界!” program 的目的是介绍初学者编程 TPK 的目的是一样的,没有实际应用。
Algorithm:
input 11 numbers into a sequence A
reverse sequence A
for each item in sequence A
call a function to do an operation
if result overflows
alert user
else
print result
C
// C program to implement TPK algorithm
#include
#include
// f(x) = sqrt(|x|) + 5*x**3
double f (double x)
{
return (sqrt(fabs(x)) + 5.0 * pow(x, 3.0));
}
int main (int argc, char* argv[])
{
double y;
int i;
// Read in the values of the array A
double A[11] = {7.9, 7.3, 20.9, 112.0, 5.0, 3.0, 2.9, 9.0, 21.7, 31.2, 4.1};
// In reverse order, apply "f"
// to each element of A and print
for (i=10; i>=0; i--)
{
y = f (A[i]);
if (y > 400.0)
{
printf ("%d TOO LARGE\n", i);
}
else
{
printf ("%d %f\n", i, y);
}
}
return (0);
}
Java
// Java program to implement TPK algorithm
import java.util.*;
import java.io.*;
public class TPKA {
public static void main(String... args) {
double[] input = {7.9, 7.3, 20.9, 112.0, 5.0, 3.0, 2.9, 9.0, 21.7, 31.2, 4.1};
for(int j = 10; j >= 0; j--) {
double y = f(input[j]);
if( y < 400.0) {
System.out.printf("%d %.2f\n", j, y);
} else {
System.out.printf("%d %s\n", j, "TOO LARGE");
}
}
}
private static double f(double x) {
return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));
}
}
Python
# Python program to implement TPK algorithm
def f(x):
return abs(x) ** 0.5 + 5 * x**3
def main():
s = [7.9, 7.3, 20.9, 112.0, 5.0, 3.0, 2.9, 9.0, 21.7, 31.2, 4.1]
s.reverse()
i = 10
for x in s:
result = f(x)
if result > 400:
print('%d %s' % (i, "TOO LARGE"))
i = i-1
else:
print('%d %f' % (i, result))
i = i-1
print('')
if __name__ == '__main__':
main()
Output:
10 346.629846
9 TOO LARGE
8 TOO LARGE
7 TOO LARGE
6 123.647939
5 136.732051
4 TOO LARGE
3 TOO LARGE
2 TOO LARGE
1 TOO LARGE
0 TOO LARGE
参考资料: http : //cs.fit.edu/~ryan/compare/tpk-c.html