1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
|
//===--- 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
//
//===----------------------------------------------------------------------===//
extension Numeric where Magnitude: FloatingPoint {
/// Test if `self` and `other` are approximately equal.
///
/// `true` if `self` and `other` are equal, or if they are finite and
/// ```
/// norm(self - other) <= relativeTolerance * scale
/// ```
/// where `scale` is
/// ```
/// max(norm(self), norm(other), .leastNormalMagnitude)
/// ```
///
/// The default value of `relativeTolerance` is `.ulpOfOne.squareRoot()`,
/// which corresponds to expecting "about half the digits" in the computed
/// results to be good. This is the usual guidance in numerical analysis,
/// if you don't know anything about the computation being performed, but
/// is not suitable for all use cases.
///
/// Mathematical Properties:
/// ------------------------
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _reflexive_ for
/// non-exceptional values (such as NaN).
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _symmetric_.
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__
/// _transitive_. Because of this, approximately equality is __not an
/// equivalence relation__, even when restricted to non-exceptional values.
///
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - For any point `a`, the set of values that compare approximately equal
/// to `a` is _convex_. (Under the assumption that the `.magnitude`
/// property implements a valid norm.)
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is _scale invariant_,
/// so long as no underflow or overflow has occured, and no exceptional
/// value is produced by the scaling.
///
/// See Also:
/// -------
/// - `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:norm:])`
///
/// - Parameters:
///
/// - other: The value to which `self` is compared.
///
/// - relativeTolerance: The tolerance to use for the comparison.
/// Defaults to `.ulpOfOne.squareRoot()`.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - norm: The [norm] to use for the comparison.
/// Defaults to `\.magnitude`.
///
/// [norm]: https://en.wikipedia.org/wiki/Norm_(mathematics)
@inlinable @inline(__always)
public func isApproximatelyEqual(
to other: Self,
relativeTolerance: Magnitude = Magnitude.ulpOfOne.squareRoot(),
norm: (Self) -> Magnitude = \.magnitude
) -> Bool {
return isApproximatelyEqual(
to: other,
absoluteTolerance: relativeTolerance * Magnitude.leastNormalMagnitude,
relativeTolerance: relativeTolerance,
norm: norm
)
}
/// Test if `self` and `other` are approximately equal with specified tolerances.
///
/// `true` if `self` and `other` are equal, or if they are finite and either
/// ```
/// (self - other).magnitude <= absoluteTolerance
/// ```
/// or
/// ```
/// (self - other).magnitude <= relativeTolerance * scale
/// ```
/// where `scale` is `max(self.magnitude, other.magnitude)`.
///
/// Mathematical Properties:
/// ------------------------
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
/// is _reflexive_ for non-exceptional values (such as NaN).
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:)`
/// is _symmetric_.
///
/// - `isApproximatelyEqual(to:relativeTolerance:norm:)` is __not__
/// _transitive_. Because of this, approximately equality is __not an
/// equivalence relation__, even when restricted to non-exceptional values.
///
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - For any point `a`, the set of values that compare approximately equal
/// to `a` is _convex_. (Under the assumption that `norm` implements a
/// valid norm, which cannot be checked by this function.)
///
/// See Also:
/// -------
/// - `isApproximatelyEqual(to:[relativeTolerance:])`
///
/// - Parameters:
///
/// - other: The value to which `self` is compared.
///
/// - absoluteTolerance: The absolute tolerance to use in the comparison.
///
/// This value should be non-negative and finite.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - relativeTolerance: The relative tolerance to use in the comparison.
/// Defaults to zero.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
@inlinable @inline(__always)
public func isApproximatelyEqual(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0
) -> Bool {
self.isApproximatelyEqual(
to: other,
absoluteTolerance: absoluteTolerance,
relativeTolerance: relativeTolerance,
norm: \.magnitude
)
}
}
extension AdditiveArithmetic {
/// Test if `self` and `other` are approximately equal with specified
/// tolerances and norm.
///
/// `true` if `self` and `other` are equal, or if they are finite and either
/// ```
/// norm(self - other) <= absoluteTolerance
/// ```
/// or
/// ```
/// norm(self - other) <= relativeTolerance * scale
/// ```
/// where `scale` is `max(norm(self), norm(other))`.
///
/// Mathematical Properties:
/// ------------------------
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
/// is _reflexive_ for non-exceptional values (such as NaN).
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
/// is _symmetric_.
///
/// - `isApproximatelyEqual(to:absoluteTolerance:relativeTolerance:norm:)`
/// is __not__ _transitive_. Because of this, approximately equality is
/// __not an equivalence relation__, even when restricted to
/// non-exceptional values.
///
/// This means that you must not use approximate equality to implement
/// a conformance to Equatable, as it will violate the invariants of
/// code written against that protocol.
///
/// - For any point `a`, the set of values that compare approximately equal
/// to `a` is _convex_ (under the assumption that `norm` implements a
/// valid norm, which cannot be checked by this function or a protocol).
///
/// See Also:
/// -------
/// - `isApproximatelyEqual(to:[relativeTolerance:norm:])`
/// - `isApproximatelyEqual(to:absoluteTolerance:[relativeTolerance:])`
///
/// - Parameters:
///
/// - other: The value to which `self` is compared.
///
/// - absoluteTolerance: The absolute tolerance to use in the comparison.
///
/// This value should be non-negative and finite.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance, even
/// one out of range.
///
/// - relativeTolerance: The relative tolerance to use in the comparison.
/// Defaults to zero.
///
/// This value should be non-negative and less than or equal to 1.
/// This constraint on is only checked in debug builds, because a
/// mathematically well-defined result exists for any tolerance,
/// even one out of range.
///
/// - norm: The norm to use for the comparison.
/// Defaults to `\.magnitude`.
///
/// For example, if we wanted to test if a complex value was inside a
/// circle of radius 0.001 centered at (1 + 0i), we could use:
/// ```
/// z.isApproximatelyEqual(
/// to: 1,
/// absoluteTolerance: 0.001,
/// norm: \.length
/// )
/// ```
/// (if we used the default norm, `.magnitude`, we would be testing if
/// `z` were inside a square region instead.)
@inlinable
public func isApproximatelyEqual<Magnitude>(
to other: Self,
absoluteTolerance: Magnitude,
relativeTolerance: Magnitude = 0,
norm: (Self) -> Magnitude
) -> Bool
// TODO: constraint should really be weaker than FloatingPoint,
// but we need to have `isFinite` for it to work correctly with
// floating-point magnitudes in generic contexts, which is the
// most common case. The fix for this is to lift the isFinite
// requirement to Numeric in the standard library, but that's
// source-breaking, so requires an ABI rumspringa.
where Magnitude: FloatingPoint {
assert(
absoluteTolerance >= 0 && absoluteTolerance.isFinite,
"absoluteTolerance should be non-negative and finite, " +
"but is \(absoluteTolerance)."
)
assert(
relativeTolerance >= 0 && relativeTolerance <= 1,
"relativeTolerance should be non-negative and <= 1, " +
"but is \(relativeTolerance)."
)
if self == other { return true }
let delta = norm(self - other)
let scale = max(norm(self), norm(other))
let bound = max(absoluteTolerance, scale*relativeTolerance)
return delta.isFinite && delta <= bound
}
}
|