Data files · comparison
Comparing Two Files: Line Diffs and Numeric Tolerances
Two output files from supposedly identical runs rarely match byte for byte. A timestamp differs, a number changes in its last digit, a line ending was converted. Comparing files well means choosing the right level of strictness first and the tool second. This page describes three levels, from an exact byte check to a diff that understands numbers, and shows how a line diff actually finds its answer. It is one of the practical techniques collected under Data and files.
Level one: are they identical?
The cheapest test reads both files in blocks and stops at the first mismatch. If the sizes differ, no reading is needed. When one of the files is remote or very large, compute a cryptographic hash of each and compare the short digests instead. A match on a strong hash is, for practical purposes, proof of identity; a mismatch proves a difference but says nothing about where it lies.
import hashlib
def digest(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(65536), b""):
h.update(block)
return h.hexdigest()
same = digest("a.dat") == digest("b.dat")
Level two: which lines differ?
A line diff treats each file as a list of lines and looks for the longest common subsequence, the largest set of lines that appear in both files in the same order. Everything outside that subsequence is either a deletion from the first file or an insertion in the second.
A small example makes the idea concrete. Let file A hold the lines a, b, c, d and file B hold a, c, d, e. The common lines in order are a, c, d, a subsequence of length 3. Line b appears only in A, so it was deleted, and line e appears only in B, so it was added. The diff reports exactly two changes, not four.
The usual algorithm fills a table in which cell (i, j) holds the length of the longest common subsequence of the first i lines of A and the first j lines of B. If the two current lines are equal the cell is the diagonal value plus 1; otherwise it is the larger of the cell above and the cell to the left. Walking back from the bottom-right corner recovers the changes. The table costs time and memory proportional to the product of the two line counts, which is why production tools use refinements for very long files.
Before diffing, normalize what does not matter. Strip trailing whitespace, convert line endings, and optionally drop lines that hold only a date or a run time. Otherwise one volatile line hides the useful differences.
Level three: do the numbers agree?
Numeric output calls for a different notion of equal. Two programs that sum the same values in a different order produce results that differ near the 16th digit, and a text diff flags every such line. A tolerance-based comparison parses each field and accepts a pair x, y when |x − y| ≤ atol + rtol × |y|, with a small absolute tolerance for values near zero and a relative one for the rest.
import numpy as np
a = np.loadtxt("a.dat")
b = np.loadtxt("b.dat")
bad = ~np.isclose(a, b, rtol=1e-9, atol=1e-12)
print(bad.sum(), "entries differ")
rows, cols = np.nonzero(bad)
Report the position and size of the worst disagreement, the maximum of |x − y| over the file, rather than a bare yes or no. A maximum difference of 3 × 10⁻¹⁵ and one of 0.4 call for very different reactions.
Choosing tolerances
There is no universal value. As a rule of thumb, a relative tolerance a few orders of magnitude above machine epsilon (about 2.2 × 10⁻¹⁶ for doubles) suits a deterministic calculation reordered by a compiler or thread count. Iterative solvers that stop at a user-set threshold need a tolerance tied to that threshold, because their answers legitimately differ by about that amount.
Structure matters too. If the files have a different number of rows or columns, report that first and stop; comparing misaligned data produces noise. Reading the files into matrices is covered under reading spreadsheet files into a matrix, and converting text fields to numbers is the subject of ASCII to double conversion. Floating-point terms are defined in the glossary.