[Math] ==~ operator applies to any <AlmostEquatable, EquatableWithinEpsilon>
This commit is contained in:
parent
1d1e5134d8
commit
58dfb3f787
1 changed files with 29 additions and 12 deletions
|
@ -9,19 +9,36 @@
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
public typealias Float = Swift.Float
|
public typealias Float = Swift.Float
|
||||||
|
public typealias Double = Swift.Double
|
||||||
|
|
||||||
/** Acceptable tolerance for Float equality. */
|
public protocol AlmostEquatable {
|
||||||
let Epsilon: Float = 1e-6
|
@warn_unused_result
|
||||||
|
func ==~(lhs: Self, rhs: Self) -> Bool
|
||||||
extension Float {
|
|
||||||
/** Test that `other` is almost equal (i.e. within the +/- Epsilon) to `self`. */
|
|
||||||
func almostEqual(other: Float) -> Bool {
|
|
||||||
return other >= (self - Epsilon) && other <= (self + Epsilon)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Custom operator for almost-equality of floats. */
|
public protocol EquatableWithinEpsilon: Strideable {
|
||||||
infix operator =~ { associativity left precedence 130 }
|
static var Epsilon: Self.Stride { get }
|
||||||
public func =~(lhs: Float, rhs: Float) -> Bool {
|
}
|
||||||
return lhs.almostEqual(rhs)
|
|
||||||
|
extension Float: EquatableWithinEpsilon {
|
||||||
|
public static let Epsilon: Float.Stride = 1e-8
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Double: EquatableWithinEpsilon {
|
||||||
|
public static let Epsilon: Double.Stride = 1e-16
|
||||||
|
}
|
||||||
|
|
||||||
|
private func almostEqual<T: EquatableWithinEpsilon>(lhs: T, _ rhs: T, epsilon: T.Stride) -> Bool {
|
||||||
|
return abs(lhs - rhs) <= epsilon
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Almost-equality of floating point types. */
|
||||||
|
infix operator ==~ { associativity left precedence 130 }
|
||||||
|
public func ==~<T: protocol<AlmostEquatable, EquatableWithinEpsilon>>(lhs: T, rhs: T) -> Bool {
|
||||||
|
return almostEqual(lhs, rhs, epsilon: T.Epsilon)
|
||||||
|
}
|
||||||
|
|
||||||
|
infix operator !==~ { associativity left precedence 130 }
|
||||||
|
public func !==~<T: AlmostEquatable>(lhs: T, rhs: T) -> Bool {
|
||||||
|
return !(lhs ==~ rhs)
|
||||||
}
|
}
|
Loading…
Add table
Add a link
Reference in a new issue