XRationals.jl
Exact rational arithmetic with IEEE-like special values (NaN, Inf, -Inf), overflow-safe saturation, lazy normalization, and zero heap allocation.
Overview
XRationals.jl provides four rational number types in two families:
| Type | Alias | Backing | Overflow | Normalization |
|---|---|---|---|---|
XRational32 | Qx32 | Int32 | Saturates to Inf/NaN | Lazy (Int64 intermediate) |
XRational64 | Qx64 | Int64 | Saturates to Inf/NaN | Lazy (Int128 intermediate) |
Rational32 | (internal) | Int32 | Throws OverflowError | Eager (always canonical) |
Rational64 | (internal) | Int64 | Throws OverflowError | Eager (always canonical) |
Choosing a type
- Need IEEE-like robustness and speed? Use
Qx32/Qx64. Overflow saturates to Inf/NaN, and lazy normalization gives 3-13x speedups overRational{Int}for chained arithmetic. - Need strict error detection?
Rational32/Rational64are available internally. Overflow throws immediately.
Quick start
using XRationals
# Basic exact arithmetic
a = Qx32(2, 3)
b = Qx32(5, 7)
a + b # 29//21
a * b # 10//21
a ^ 3 # 8//27
# IEEE-like special values
Qx32(1, 0) # Inf
Qx32(-1, 0) # -Inf
Qx32(0, 0) # NaN
# Overflow saturates instead of crashing
Qx32(typemax(Int32), 1) + 1 # Inf
# Lazy normalization: GCD deferred until display
Qx64(6, 8) == Qx64(3, 4) # true (cross-multiply comparison)Key features
- Zero heap allocation: all arithmetic uses fixed-width integers (Int32/Int64/Int128/Int256)
- Lazy normalization: GCD is deferred until display, hashing, or conversion
typeminrejection: constructors rejecttypemin(Int32)andtypemin(Int64)to prevent silent negation overflow- Fused multiply-add:
fma(x, y, z)computesx*y + zwith exact intermediate precision - Cross-width conversion:
Qx32(x::Qx64)finds the best Int32 approximation via Stern-Brocot mediants - IEEE ordering: NaN sorts last, Inf/-Inf compare correctly