Arrays and matrix math
The first thing a numerical program does is arithmetic on arrays, and the first thing a C++ programmer notices about Fortran is that the language has them. This page writes the same eight computations twice, builds both with the compilers in this image, and compares the output byte for byte.
The task
A vector v of eight values one to eight and a 3 by 3 matrix A whose columns are 1 2 3, 4 5 6 and 7 8 9. The program prints the sum, the mean, the maximum and the dot product of the vector, the product A v of the matrix with the first three values, the trace, the first row of the transpose and a strided slice of the vector. Eight numbers that a reader can check by hand, which is what makes the two outputs comparable at all.
The Fortran program
The file arrays.f90:
program arrays_f
use, intrinsic :: iso_fortran_env, only: dp => real64
implicit none
integer, parameter :: n = 8
real(dp) :: v(n), a(3, 3), w(3), at(3, 3)
integer :: i
v = [(real(i, dp), i = 1, n)]
a = reshape([1.0_dp, 2.0_dp, 3.0_dp, 4.0_dp, 5.0_dp, 6.0_dp, 7.0_dp, 8.0_dp, 9.0_dp], [3, 3])
print '(a,f8.2)', 'sum ', sum(v)
print '(a,f8.2)', 'mean ', sum(v) / real(n, dp)
print '(a,f8.2)', 'max ', maxval(v)
print '(a,f8.2)', 'dot ', dot_product(v, v)
w = matmul(a, v(1:3))
print '(a,3f8.2)', 'A*v ', w
print '(a,f8.2)', 'trace ', a(1, 1) + a(2, 2) + a(3, 3)
at = transpose(a)
print '(a,3f8.2)', 'A^T row 1', at(1, :)
print '(a,3f8.2)', 'v(2:8:3) ', v(2:8:3)
end program arrays_f
gfortran -Wall -Wextra -std=f2018 arrays.f90 -o arrays_f
./arrays_f
The C++ program
The same eight numbers, with a std::vector for each array and the standard algorithms for the reductions. The matrix-vector product has no algorithm in the standard library, so it is two loops, which is the first real difference between the two programs.
The file arrays.cpp:
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <vector>
int main() {
const int n = 8;
std::vector<double> v(n);
for (int i = 0; i < n; ++i) {
v[i] = i + 1;
}
const std::vector<std::vector<double>> a = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
double sum = std::accumulate(v.begin(), v.end(), 0.0);
std::printf("%-9s%8.2f\n", "sum", sum);
std::printf("%-9s%8.2f\n", "mean", sum / n);
std::printf("%-9s%8.2f\n", "max", *std::max_element(v.begin(), v.end()));
std::printf("%-9s%8.2f\n", "dot", std::inner_product(v.begin(), v.end(), v.begin(), 0.0));
std::vector<double> w(3, 0.0);
for (int i = 0; i < 3; ++i) {
for (int k = 0; k < 3; ++k) {
w[i] += a[i][k] * v[k];
}
}
std::printf("%-9s%8.2f%8.2f%8.2f\n", "A*v", w[0], w[1], w[2]);
std::printf("%-9s%8.2f\n", "trace", a[0][0] + a[1][1] + a[2][2]);
std::printf("%-9s%8.2f%8.2f%8.2f\n", "A^T row 1", a[0][0], a[1][0], a[2][0]);
std::printf("%-9s%8.2f%8.2f%8.2f\n", "v(2:8:3)", v[1], v[4], v[7]);
return 0;
}
g++ -std=c++23 -Wall -Wextra arrays.cpp -o arrays_cpp
./arrays_cpp
The output
Both programs print the same format, so the outputs can be compared with diff instead of by eye:
./arrays_f > f.txt
./arrays_cpp > c.txt
diff f.txt c.txt
(no output: the two files are identical)
sum 36.00
mean 4.50
max 8.00
dot 204.00
A*v 30.00 36.00 42.00
trace 15.00
A^T row 1 1.00 2.00 3.00
v(2:8:3) 2.00 5.00 8.00
What differs
The two programs are the same length, within a line or two, and the numbers agree. Four things differ, and each of them is a habit that a programmer moving between the languages has to unlearn.
The matrix literal. Fortran fills a matrix column by column, so the nine values in RESHAPE are 1 2 3 in the first column and the source does not look like the matrix. C++ nests row by row, so its literal looks like the printed matrix and its storage is the transpose of the Fortran one. Both programs print A^T row 1 as 1 2 3, and the C++ reader who writes the literal the way the matrix looks gets the same answer with a different memory order. The next page measures what that order costs.
The reductions. Fortran has SUM, MAXVAL and DOT_PRODUCT in the language; C++ needs <numeric> and <algorithm> for two of them and an accumulator for the rest. Neither of those differences is about speed at this size, and both are about how much a reader has to know: the Fortran names are part of the language a reader of any Fortran program already knows.
The matrix product. MATMUL(A, v) against two nested loops. The Fortran version is one line and was measured at about four times the speed of a hand-written loop in lesson 121, because the compiler calls a library routine that blocks the loops for the cache. A C++ program that wants the same calls a library: the standard has none, which is why a C++ numerical project starts with a dependency and a Fortran one does not.
The slice. v(2:8:3) is three values with a stride, in one expression, and it can be an argument to a procedure or the left side of an assignment. C++ writes three subscripts, or a loop over an iterator with a step, and the three subscripts are what a reader checks. The Fortran form has a trap of its own: a section is a copy where C++ would pass a view, which is lesson 034, and the difference shows up the moment the section is written to.
Exercises
- Print the matrix twice, once as stored and once transposed, in both languages. Which program has to change more?
- Replace MATMUL with three loops in Fortran and remove the loops in C++ by writing a matvec function. Do the outputs still agree?
- Add a fourth column to the matrix in both programs. How many places change in each?
- Make the C++ vector a std::array<double, 8> and the Fortran array a fixed one. Which program needs fewer changes, and which one can still take a size from the command line?
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and G++ (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev