docs(ApproximateEquality): address maintainer review feedback on abstraction and tolerances

Signed-off-by: reginaldalfret <reginaldalfret@gmail.com>
This commit is contained in:
reginaldalfret committed 2026-10-08 17:46:40 +05:30
1 parent 0d1ccaf0d3
commit 8630961065
2 files changed
+97 -27

No files matched your search

@@ -1,13 +1,17 @@
# Approximate Equality
Compare floating-point and numerical values up to a tolerance.
Test whether two values agree within a specified tolerance.
## Overview
Floating-point arithmetic is not exact, so two values that are mathematically
equal may differ slightly once they have been computed. Comparing such values
with `==` is usually a mistake: the test will fail for inputs that are equal
in every way that matters to your program.
In numerical computing, mathematical equality often diverges from computed
equality. Rounding in floating-point arithmetic is one common cause, but many
nontrivial numerical algorithms also have inherent truncation or discretization
errors, and empirical measurements carry uncertainty to begin with. In these
scenarios, exact equality (`==`) may be too strict or inappropriate, and an
approximate equality comparison is needed instead. Conversely, exact equality
remains entirely appropriate when checking for identical values, sentinel states,
or integers.
`RealModule` provides a family of `isApproximatelyEqual` methods that test
whether two values are within a tolerance of one another. They are available
@@ -23,6 +27,52 @@ x == 0.3 // false
x.isApproximatelyEqual(to: 0.3) // true
```
### Comparing non-Numeric types with a custom norm
The approximate equality API is not limited to scalar numbers or `Numeric`
types. Any type conforming to `AdditiveArithmetic` can be compared once you
supply a suitable norm function mapping differences to a `FloatingPoint`
magnitude.
For example, consider a 2D geometric vector or point type representing spatial
displacements:
```swift
struct Vector2D: AdditiveArithmetic, Equatable {
var x: Double
var y: Double
static var zero: Vector2D {
Vector2D(x: 0, y: 0)
}
static func + (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
Vector2D(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
static func - (lhs: Vector2D, rhs: Vector2D) -> Vector2D {
Vector2D(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
}
// Compare vectors using the Euclidean distance (L2 norm):
let v1 = Vector2D(x: 1.0, y: 2.0)
let v2 = Vector2D(x: 1.000000001, y: 1.999999999)
let areClose = v1.isApproximatelyEqual(
to: v2,
absoluteTolerance: 1e-6,
norm: { v in (v.x * v.x + v.y * v.y).squareRoot() }
)
// areClose == true
```
Because `Vector2D` is not `Numeric` (it does not define multiplication of
vectors to produce a vector), it cannot use the standard `Numeric.isApproximatelyEqual`
overload. However, because vector subtraction forms a difference vector in an
additive space, the general `AdditiveArithmetic` overload evaluates the custom
norm directly.
### Choosing a tolerance
The simplest method uses a _relative_ tolerance:
@@ -52,9 +102,16 @@ information about the computation, but it is not appropriate for every use
case, so you should pass an explicit value when you can estimate how much error
your computation introduces.
A relative tolerance does not work well when comparing against zero, because
the scale of zero is zero. To handle values near zero, use the overload that
also takes an _absolute_ tolerance:
#### Absolute versus relative tolerance
A relative tolerance scales with the magnitude of the operands, making it
effective across numbers of very small or very large scale. However, a pure
relative tolerance fails when comparing against zero or numbers much smaller
than the surrounding computation, because `scale` approaches zero and shrinks
the allowable difference to near zero.
To handle values near zero, use the overload that also accepts an _absolute_
tolerance:
```swift
public func isApproximatelyEqual(
@@ -77,20 +134,22 @@ or
(self - other).magnitude <= relativeTolerance * scale
```
where `scale` is `max(self.magnitude, other.magnitude)`. The relative tolerance
defaults to zero here, so by passing only an absolute tolerance you get a plain
absolute comparison. A common pattern is to supply both, using the absolute
tolerance to bound the comparison near zero and the relative tolerance
elsewhere:
where `scale` is `max(self.magnitude, other.magnitude)`.
```swift
let error = 1e-8
result.isApproximatelyEqual(
to: expected,
absoluteTolerance: error,
relativeTolerance: error
)
```
When choosing values:
- Use **relative tolerance** when the allowed error is proportional to the
magnitude of the values being computed (e.g. general floating-point arithmetic).
- Use **absolute tolerance** when values can be near zero, or when the error
is independent of the scale of the inputs (e.g. fixed measurement resolution).
- Supplying both allows the absolute tolerance to govern comparisons near
zero, while the relative tolerance takes over once values grow beyond
`absoluteTolerance / relativeTolerance`.
Setting `absoluteTolerance == relativeTolerance` is typically appropriate only
when values are expected to lie on an integral or unit-spaced grid due to
algorithmic considerations (where `1.0` represents the base unit scale). For
general computations, the two tolerances should be chosen independently based on
the scale of the problem and the expected precision.
### Special values
@@ -124,9 +183,23 @@ public func isApproximatelyEqual<Magnitude>(
where Magnitude: FloatingPoint
```
For a complex value, the default norm `\.magnitude` measures the difference
inside a square region. To test instead whether a value lies inside a circle of
radius `0.001` centered at `1 + 0i`, pass the Euclidean length as the norm:
#### Complex magnitude vs other norms
For complex numbers, the default norm is `\.magnitude`, which computes the
infinity-norm (`max(abs(real), abs(imaginary))`).
A major numerical advantage of `\.magnitude` for complex values is that it is
finite and non-zero for any finite non-zero value:
- Unlike Euclidean length (`\.length`, $\sqrt{x^2 + y^2}$), which can overflow
to infinity if $x^2 + y^2$ exceeds the maximum representable finite value or
underflow if both components are tiny, `\.magnitude` never overflows or underflows
for finite numbers.
- It avoids intermediate squaring, square roots, or the complex scaling logic of
`hypot`, making it robust even when handling very poorly scaled values.
If you specifically need to test whether a complex number lies inside a circular
disk of radius `0.001` centered at `1 + 0i` rather than a square box, you can
pass the Euclidean length as the norm:
```swift
import ComplexModule
-3
View File
@@ -70,9 +70,6 @@ Not having this protocol is a significant missing feature for numerical computin
## Approximate equality
Because floating-point arithmetic is inexact, two values that are
mathematically equal often differ slightly once computed, so comparing them
with `==` is usually a mistake.
`RealModule` provides a family of `isApproximatelyEqual` methods that test
whether two values agree up to a relative or absolute tolerance: