apple / apple/swift-numerics

Add isApproximatelyEqual for RandomAccessCollection

Open
#334 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Swift
Stars
1.9k
Forks
181
Avg merge
2d 5h
Merged PRs (30d)
6

Description

I think it would be useful to add `isApproximatelyEqual` for `RandomAccessCollection`. When working with numerical computations on collections of floating-point values (e.g., vectors, matrices represented as arrays), it's common in tests to need element-wise approximate equality comparisons. The API would mirror the existing scalar versions:

```swift
extension RandomAccessCollection where Element: Numeric, Element.Magnitude: FloatingPoint {
@inlinable @inline(__always)
public func isApproximatelyEqual(
to other: Self,
relativeTolerance: Element.Magnitude = Element.Magnitude.ulpOfOne.squareRoot(),
norm: (Element) -> Element.Magnitude = \.magnitude
) -> Bool {
return isApproximatelyEqual(
to: other,
absoluteTolerance: relativeTolerance * Element.Magnitude.leastNormalMagnitude,
relativeTolerance: relativeTolerance,
norm: norm
)
}

@inlinable @inline(__always)
public func isApproximatelyEqual(
to other: Self,
absoluteTolerance: Element.Magnitude,
relativeTolerance: Element.Magnitude = 0
) -> Bool {
return isApproximatelyEqual(
to: other,
absoluteTolerance: absoluteTolerance,
relativeTolerance: relativeTolerance,
norm: \.magnitude
)
}
}

extension RandomAccessCollection where Element: AdditiveArithmetic {
@inlinable
public func isApproximatelyEqual(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0,
norm: (Element) -> Magnitude
) -> Bool
where Magnitude: FloatingPoint {
guard self.count == other.count else { return false }
for (lhs, rhs) in zip(self, other) {
if !lhs.isApproximatelyEqual(
to: rhs,
absoluteTolerance: absoluteTolerance,
relativeTolerance: relativeTolerance,
norm: norm
) {
return false
}
}
return true
}
}

```

I'm happy to submit a PR with tests if this sounds reasonable.

Contributor guide

Open the contributing guide

Research direction

The issue provides the proposed RandomAccessCollection API and asks for tests. Start by locating the existing scalar isApproximatelyEqual entry points, then add collection coverage for equal counts and element-wise comparisons. Done means the overloads are implemented and the proposed tests pass.

Written by the indexing model from the issue text.

Assessment

Tech stack
swift
Domain
backend-api-design
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.