diff --git a/Sources/RealModule/ApproximateEquality.swift b/Sources/RealModule/ApproximateEquality.swift new file mode 100644 index 0000000..0e0aa19 --- /dev/null +++ b/Sources/RealModule/ApproximateEquality.swift @@ -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 { + 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 = .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 + } + } +} diff --git a/Tests/ComplexTests/ApproximateEqualityTests.swift b/Tests/ComplexTests/ApproximateEqualityTests.swift new file mode 100644 index 0000000..7ea15c8 --- /dev/null +++ b/Tests/ComplexTests/ApproximateEqualityTests.swift @@ -0,0 +1,38 @@ +import Numerics +import XCTest + +final class ElementaryFunctionTests: XCTestCase { + + func testSpecials(tolerance tol: Tolerance) { + XCTAssertTrue(Complex.zero.approximatelyEquals(.zero, tolerance: tol)) + XCTAssertTrue(Complex.zero.approximatelyEquals(-.zero, tolerance: tol)) + XCTAssertTrue((-Complex.zero).approximatelyEquals(.zero, tolerance: tol)) + XCTAssertTrue((-Complex.zero).approximatelyEquals(-.zero, tolerance: tol)) + XCTAssertTrue(Complex.infinity.approximatelyEquals(.infinity, tolerance: tol)) + XCTAssertTrue((-Complex.infinity).approximatelyEquals(-.infinity, tolerance: tol)) + // Complex has a single point at infinity. + XCTAssertTrue(Complex.infinity.approximatelyEquals(-.infinity, tolerance: tol)) + XCTAssertTrue((-Complex.infinity).approximatelyEquals(.infinity, tolerance: tol)) + } + + func testSpecials(_ type: T.Type) { + XCTAssertTrue(Complex.zero.approximatelyEquals(.zero)) + XCTAssertTrue(Complex.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) + } +} diff --git a/Tests/ComplexTests/ArithmeticTests.swift b/Tests/ComplexTests/ArithmeticTests.swift index ba88d94..a2ad64b 100644 --- a/Tests/ComplexTests/ArithmeticTests.swift +++ b/Tests/ComplexTests/ArithmeticTests.swift @@ -165,12 +165,10 @@ final class ArithmeticTests: XCTestCase { let a: Complex let b: Complex let c: Complex - let allowSmallError: Bool - init(_ a: Complex, _ b: Complex, _ c: Complex, allowSmallError: Bool = false) { + init(_ a: Complex, _ b: Complex, _ c: Complex) { 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 diff --git a/Tests/RealTests/ApproximateEqualityTests.swift b/Tests/RealTests/ApproximateEqualityTests.swift new file mode 100644 index 0000000..40a4a3c --- /dev/null +++ b/Tests/RealTests/ApproximateEqualityTests.swift @@ -0,0 +1,117 @@ +import RealModule +import XCTest + +final class ElementaryFunctionTests: XCTestCase { + + func testSpecials(tolerance tol: Tolerance) { + 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(_ 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(_ 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(_ 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) + } +} diff --git a/Tests/RealTests/IntegerExponentTests.swift b/Tests/RealTests/IntegerExponentTests.swift index fcf0011..3d6a636 100644 --- a/Tests/RealTests/IntegerExponentTests.swift +++ b/Tests/RealTests/IntegerExponentTests.swift @@ -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)) diff --git a/Tests/RealTests/RealTestSupport.swift b/Tests/RealTests/RealTestSupport.swift index 8296c43..fb446d4 100644 --- a/Tests/RealTests/RealTestSupport.swift +++ b/Tests/RealTests/RealTestSupport.swift @@ -81,3 +81,19 @@ func assertClose( 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(using g: inout G) -> FloatingPointSign { + [.plus,.minus].randomElement(using: &g)! + } +}