Euclidean Affine Functions and Applications to Calendar Algorithms
Cassio Neri, Lorenz Schneider
TL;DR
The paper develops a systematic framework for Euclidean affine functions $f(r)=\frac{\alpha r+\beta}{\delta}$ and residuals $\mathring{f}(r)=(\alpha r+\beta)\%\delta$, deriving algebraic relations and CPU-friendly approximations that accelerate common integer-divide-and-remainder tasks. It then builds a modular calendar framework based on rata die functions, introducing a computational calendar and a series of efficient mappings that translate Gregorian dates into fast, unsigned arithmetic and back. The main contribution is a set of fast EAF-based evaluation strategies (including fast division and fast residuals) and a generic, provably correct approach to calendar arithmetic that yields speedups over widely used libraries such as glibc, Boost, libc++, OpenJDK, and .NET. Practically, these methods enable substantially faster Gregorian calendar computations and date conversions on modern CPUs, with broad implications for date/time handling in software systems. The work also provides a unified, mathematically grounded pathway to derive fast, low-latency date transformations across epochs and calendar representations.
Abstract
We study properties of Euclidean affine functions (EAFs), namely those of the form $f(r) = (α\cdot r + β)/δ$, and their closely related expression $\mathring{f}(r) = (α\cdot r + β)\%δ$, where $r$, $α$, $β$ and $δ$ are integers, and where $/$ and $\%$ respectively denote the quotient and remainder of Euclidean division. We derive algebraic relations and numerical approximations that are important for the efficient evaluation of these expressions in modern CPUs. Since simple division and remainder are particular cases of EAFs (when $α= 1$ and $β= 0$), the optimisations proposed in this paper can also be appplied to them. Such expressions appear in some of the most common tasks in any computer system, such as printing numbers, times and dates. We use calendar calculations as the main application example because it is richer with respect to the number of EAFs employed. Specifically, the main application presented in this article relates to Gregorian calendar algorithms. We will show how they can be implemented substantially more efficiently than is currently the case in widely used C, C++, C# and Java open source libraries. Gains in speed of a factor of two or more are common.
