mirror of
https://github.com/apple/swift-numerics
synced 2026-11-28 05:14:31 +00:00
First crack at dusting approximate comparisons back off.
This commit is contained in:
1 parent
110beefe0b
commit
91ecc8a3b6
6 files changed
+229
-7
No files matched your search
@@ -0,0 +1,50 @@
|
||||
//===--- ApproximateEquality.swift ----------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A tolerance to use for approximate comparisons
|
||||
///
|
||||
/// These values are consumed by the `approximatelyEquals` method defined on `Numeric`
|
||||
/// whenever the `Magnitude` associated type conforms to floating-point.
|
||||
public enum Tolerance<T: FloatingPoint> {
|
||||
case relative(_ tolerance: T = T.ulpOfOne.squareRoot(), minimumScale: T = .leastNormalMagnitude)
|
||||
case absolute(_ tolerance: T = T.ulpOfOne.squareRoot())
|
||||
}
|
||||
|
||||
extension Numeric where Magnitude: FloatingPoint {
|
||||
/// Approximate equality comparison
|
||||
///
|
||||
/// Due to rounding of intermediate results, "the same" value computed using two different techniques
|
||||
/// frequently has a slightly different result in floating-point arithmetic. This comparison method may
|
||||
/// be helpful in these situations.
|
||||
///
|
||||
/// By default, this method performs a relative comparison with a minimum scale set to the underflow
|
||||
/// threshold and a tolerance of √ulpOfOne. This is as sensible a default as any.
|
||||
@inlinable
|
||||
public func approximatelyEquals(
|
||||
_ other: Self,
|
||||
tolerance: Tolerance<Magnitude> = .relative()
|
||||
) -> Bool {
|
||||
// If a and b are actually equal, then they are certainly *almost* equal,
|
||||
// with any allowable tolerance.
|
||||
if self == other { return true }
|
||||
let delta = (self - other).magnitude
|
||||
switch tolerance {
|
||||
case let .absolute(atol):
|
||||
assert(atol > 0 && atol.isFinite, "Absolute tolerance must be positive and finite.")
|
||||
return delta < atol
|
||||
case let .relative(rtol, floor):
|
||||
assert(rtol >= .ulpOfOne && rtol < 1, "Relative tolerance must be in [.ulpOfOne, 1).")
|
||||
assert(floor >= 0 && floor.isFinite, "Minimum scale must be positive and finite.")
|
||||
let scale = max(self.magnitude, other.magnitude, floor)
|
||||
return delta < scale*rtol
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Numerics
|
||||
import XCTest
|
||||
|
||||
final class ElementaryFunctionTests: XCTestCase {
|
||||
|
||||
func testSpecials<T: Real>(tolerance tol: Tolerance<T>) {
|
||||
XCTAssertTrue(Complex<T>.zero.approximatelyEquals(.zero, tolerance: tol))
|
||||
XCTAssertTrue(Complex<T>.zero.approximatelyEquals(-.zero, tolerance: tol))
|
||||
XCTAssertTrue((-Complex<T>.zero).approximatelyEquals(.zero, tolerance: tol))
|
||||
XCTAssertTrue((-Complex<T>.zero).approximatelyEquals(-.zero, tolerance: tol))
|
||||
XCTAssertTrue(Complex<T>.infinity.approximatelyEquals(.infinity, tolerance: tol))
|
||||
XCTAssertTrue((-Complex<T>.infinity).approximatelyEquals(-.infinity, tolerance: tol))
|
||||
// Complex has a single point at infinity.
|
||||
XCTAssertTrue(Complex<T>.infinity.approximatelyEquals(-.infinity, tolerance: tol))
|
||||
XCTAssertTrue((-Complex<T>.infinity).approximatelyEquals(.infinity, tolerance: tol))
|
||||
}
|
||||
|
||||
func testSpecials<T: Real>(_ type: T.Type) {
|
||||
XCTAssertTrue(Complex<T>.zero.approximatelyEquals(.zero))
|
||||
XCTAssertTrue(Complex<T>.zero.approximatelyEquals(-.zero))
|
||||
testSpecials(tolerance: .absolute(T.zero))
|
||||
testSpecials(tolerance: .absolute(T.greatestFiniteMagnitude))
|
||||
testSpecials(tolerance: .relative(T.ulpOfOne))
|
||||
testSpecials(tolerance: .relative(T(1).nextDown))
|
||||
}
|
||||
|
||||
func testFloat() {
|
||||
testSpecials(Float.self)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
testSpecials(Double.self)
|
||||
}
|
||||
|
||||
func testFloat80() {
|
||||
testSpecials(Float80.self)
|
||||
}
|
||||
}
|
||||
@@ -165,12 +165,10 @@ final class ArithmeticTests: XCTestCase {
|
||||
let a: Complex<Double>
|
||||
let b: Complex<Double>
|
||||
let c: Complex<Double>
|
||||
let allowSmallError: Bool
|
||||
init(_ a: Complex<Double>, _ b: Complex<Double>, _ c: Complex<Double>, allowSmallError: Bool = false) {
|
||||
init(_ a: Complex<Double>, _ b: Complex<Double>, _ c: Complex<Double>) {
|
||||
self.a = a
|
||||
self.b = b
|
||||
self.c = c
|
||||
self.allowSmallError = allowSmallError
|
||||
}
|
||||
}
|
||||
// The ten test cases from Baudin & Smith's paper. These only apply to
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import RealModule
|
||||
import XCTest
|
||||
|
||||
final class ElementaryFunctionTests: XCTestCase {
|
||||
|
||||
func testSpecials<T: Real>(tolerance tol: Tolerance<T>) {
|
||||
XCTAssertTrue(T.zero.approximatelyEquals(.zero, tolerance: tol))
|
||||
XCTAssertTrue( T.zero.approximatelyEquals(-.zero, tolerance: tol))
|
||||
XCTAssertTrue((-T.zero).approximatelyEquals(.zero, tolerance: tol))
|
||||
XCTAssertTrue((-T.zero).approximatelyEquals(-.zero, tolerance: tol))
|
||||
XCTAssertTrue( T.infinity.approximatelyEquals(.infinity, tolerance: tol))
|
||||
XCTAssertTrue((-T.infinity).approximatelyEquals(-.infinity, tolerance: tol))
|
||||
XCTAssertFalse( T.infinity.approximatelyEquals(.greatestFiniteMagnitude, tolerance: tol))
|
||||
XCTAssertFalse( T.greatestFiniteMagnitude.approximatelyEquals(.infinity, tolerance: tol))
|
||||
XCTAssertFalse((-T.infinity).approximatelyEquals(-.greatestFiniteMagnitude, tolerance: tol))
|
||||
XCTAssertFalse((-T.greatestFiniteMagnitude).approximatelyEquals(-.infinity, tolerance: tol))
|
||||
XCTAssertFalse( T.infinity.approximatelyEquals(-.infinity, tolerance: tol))
|
||||
XCTAssertFalse((-T.infinity).approximatelyEquals(.infinity, tolerance: tol))
|
||||
XCTAssertFalse( T.nan.approximatelyEquals(.nan, tolerance: tol))
|
||||
}
|
||||
|
||||
func testSpecials<T: Real>(_ type: T.Type) {
|
||||
XCTAssertTrue( T.zero.approximatelyEquals(.zero))
|
||||
XCTAssertTrue( T.zero.approximatelyEquals(-.zero))
|
||||
XCTAssertTrue((-T.zero).approximatelyEquals(.zero))
|
||||
XCTAssertTrue((-T.zero).approximatelyEquals(-.zero))
|
||||
testSpecials(tolerance: .absolute(T.leastNormalMagnitude))
|
||||
testSpecials(tolerance: .absolute(T.greatestFiniteMagnitude))
|
||||
testSpecials(tolerance: .relative(T.ulpOfOne))
|
||||
testSpecials(tolerance: .relative(T(1).nextDown))
|
||||
}
|
||||
|
||||
func testDefaults<T: Real>(_ type: T.Type) {
|
||||
let e = T.sqrt(.ulpOfOne)
|
||||
XCTAssertTrue(T(1).approximatelyEquals(1 + e))
|
||||
XCTAssertTrue(T(1).approximatelyEquals(1 - e/2))
|
||||
XCTAssertFalse(T(1).approximatelyEquals(1 + 2*e))
|
||||
XCTAssertFalse(T(1).approximatelyEquals(1 - e))
|
||||
XCTAssertTrue(T(1).approximatelyEquals(1 + e, tolerance: .relative()))
|
||||
XCTAssertTrue(T(1).approximatelyEquals(1 - e/2, tolerance: .relative()))
|
||||
XCTAssertFalse(T(1).approximatelyEquals(1 + 2*e, tolerance: .relative()))
|
||||
XCTAssertFalse(T(1).approximatelyEquals(1 - e, tolerance: .relative()))
|
||||
XCTAssertTrue(T(1).approximatelyEquals((1 + e).nextDown, tolerance: .absolute()))
|
||||
XCTAssertTrue(T(1).approximatelyEquals((1 - e).nextUp, tolerance: .absolute()))
|
||||
XCTAssertFalse(T(1).approximatelyEquals((1 + e).nextUp, tolerance: .absolute()))
|
||||
XCTAssertFalse(T(1).approximatelyEquals((1 - e).nextDown, tolerance: .absolute()))
|
||||
}
|
||||
|
||||
func testRandom<T>(_ type: T.Type) where T: FixedWidthFloatingPoint & Real {
|
||||
var g = SystemRandomNumberGenerator()
|
||||
// Generate a bunch of random values in a small interval and a tolerance
|
||||
// and use them to check that various properties that we would like to
|
||||
// hold actually do.
|
||||
var values = [1] + (0 ..< 64).map { _ in T.random(in: 1 ..< 2, using: &g) } + [2]
|
||||
values.sort()
|
||||
// We have 66 values in 1 ... 2, so if we use a tolerance of around 1/64,
|
||||
// at least some of the pairs will compare equal with tolerance.
|
||||
let tol = T.random(in: 1/64 ... 1/32, using: &g)
|
||||
// We're going to walk the values in order, validating that some common-
|
||||
// sense properties hold.
|
||||
for i in values.indices {
|
||||
// reflexivity
|
||||
XCTAssertTrue(values[i].approximatelyEquals(values[i], tolerance: .absolute(tol)))
|
||||
for j in i ..< values.endIndex {
|
||||
// commutativity
|
||||
XCTAssertTrue(
|
||||
values[i].approximatelyEquals(values[j], tolerance: .relative(tol)) ==
|
||||
values[j].approximatelyEquals(values[i], tolerance: .relative(tol))
|
||||
)
|
||||
XCTAssertTrue(
|
||||
values[i].approximatelyEquals(values[j], tolerance: .absolute(tol)) ==
|
||||
values[j].approximatelyEquals(values[i], tolerance: .absolute(tol))
|
||||
)
|
||||
// scale invariance for relative comparisons
|
||||
let scale = T(
|
||||
sign:.plus,
|
||||
exponent: T.Exponent.random(in: T.leastNormalMagnitude.exponent ... T.greatestFiniteMagnitude.exponent),
|
||||
significand: 1
|
||||
)
|
||||
XCTAssertTrue(
|
||||
(scale*values[i]).approximatelyEquals(scale*values[j], tolerance: .relative(tol)) ==
|
||||
(scale*values[j]).approximatelyEquals(scale*values[i], tolerance: .relative(tol))
|
||||
)
|
||||
}
|
||||
// if a ≤ b ≤ c, and a ≈ c, then a ≈ b and b ≈ c
|
||||
for t in [Tolerance.relative(tol), .absolute(tol)] {
|
||||
guard let left = values.firstIndex(where: {
|
||||
values[i].approximatelyEquals($0, tolerance: t)
|
||||
}) else { continue }
|
||||
let right = values.lastIndex {
|
||||
values[i].approximatelyEquals($0, tolerance: t)
|
||||
}! // don't need guard because we found left
|
||||
for j in left ... right {
|
||||
XCTAssertTrue(values[i].approximatelyEquals(values[j], tolerance: t))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFloat() {
|
||||
testSpecials(Float.self)
|
||||
testDefaults(Float.self)
|
||||
testRandom(Float.self)
|
||||
}
|
||||
|
||||
func testDouble() {
|
||||
testSpecials(Double.self)
|
||||
testDefaults(Double.self)
|
||||
testRandom(Double.self)
|
||||
}
|
||||
|
||||
func testFloat80() {
|
||||
testSpecials(Float80.self)
|
||||
testDefaults(Float80.self)
|
||||
testRandom(Float80.self)
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,11 @@
|
||||
import XCTest
|
||||
import RealModule
|
||||
|
||||
internal extension Real where Self: BinaryFloatingPoint,
|
||||
Self.RawSignificand: FixedWidthInteger {
|
||||
internal extension Real where Self: FixedWidthFloatingPoint {
|
||||
|
||||
static func testIntegerExponentCommon() {
|
||||
// TODO: replace with seedable generator, print seed.
|
||||
var g = SystemRandomNumberGenerator()
|
||||
// If x is -1, then the result is ±1 with sign chosen by parity of n.
|
||||
// Simply converting n to Real will flip parity when n is large, so
|
||||
// first check that we get those cases right.
|
||||
@@ -32,8 +34,9 @@ internal extension Real where Self: BinaryFloatingPoint,
|
||||
// underflow; we want to be sure that we get the right ±0 or ±∞
|
||||
// result.
|
||||
for _ in 0 ..< 10 {
|
||||
let x = Self.random(in: 2 ..< 4)
|
||||
let n = Int.random(in: 1 - Int(Self.leastNonzeroMagnitude.exponent) ..< .max)
|
||||
let x = Self.random(in: 2 ..< 4, using: &g)
|
||||
let nLowerBound = 1 - Int(Self.leastNonzeroMagnitude.exponent)
|
||||
let n = Int.random(in: nLowerBound ..< .max, using: &g)
|
||||
let even = n & -2
|
||||
let odd = even | 1
|
||||
assertClose( .infinity, Self.pow(x, even))
|
||||
|
||||
@@ -81,3 +81,19 @@ func assertClose<T>(
|
||||
expected, observed, allowedError: allowedError, file: file, line: line
|
||||
))
|
||||
}
|
||||
|
||||
internal protocol FixedWidthFloatingPoint: BinaryFloatingPoint
|
||||
where Exponent: FixedWidthInteger,
|
||||
RawSignificand: FixedWidthInteger { }
|
||||
|
||||
extension Float: FixedWidthFloatingPoint { }
|
||||
extension Double: FixedWidthFloatingPoint { }
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
extension Float80: FixedWidthFloatingPoint { }
|
||||
#endif
|
||||
|
||||
extension FloatingPointSign {
|
||||
static func random<G: RandomNumberGenerator>(using g: inout G) -> FloatingPointSign {
|
||||
[.plus,.minus].randomElement(using: &g)!
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user