From 7953ef315a427b1e40d6772fb5b65550a4b0f080 Mon Sep 17 00:00:00 2001 From: Stephen Canon Date: Wed, 26 Apr 2023 16:43:50 -0400 Subject: [PATCH] First pass. --- Sources/IntegerUtilities/CMakeLists.txt | 1 + .../IntegerUtilities/DivideWithRounding.swift | 9 +-- Sources/IntegerUtilities/RoundingRule.swift | 28 +++++++++ .../SaturatingArithmetic.swift | 60 +++++++++++++++++++ 4 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 Sources/IntegerUtilities/SaturatingArithmetic.swift diff --git a/Sources/IntegerUtilities/CMakeLists.txt b/Sources/IntegerUtilities/CMakeLists.txt index cd141a4..db167c7 100644 --- a/Sources/IntegerUtilities/CMakeLists.txt +++ b/Sources/IntegerUtilities/CMakeLists.txt @@ -12,6 +12,7 @@ add_library(IntegerUtilities GCD.swift Rotate.swift RoundingRule.swift + SaturatingArithmetic.swift ShiftWithRounding.swift) set_target_properties(IntegerUtilities PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) diff --git a/Sources/IntegerUtilities/DivideWithRounding.swift b/Sources/IntegerUtilities/DivideWithRounding.swift index 87fabaa..c0cf0a6 100644 --- a/Sources/IntegerUtilities/DivideWithRounding.swift +++ b/Sources/IntegerUtilities/DivideWithRounding.swift @@ -126,12 +126,13 @@ extension BinaryInteger { } } - // TODO: make this API and make it possible to implement more - // efficiently. Customization point on new/revised integer - // protocol? Shouldn't have to go through .words. + // TODO: make this API and make it possible to implement more efficiently. + // Customization point on new/revised integer protocol? Shouldn't have to + // go through .words. + /// The index of the most-significant set bit. /// - /// - Precondition: self is assumed to be non-zero (to be changed + /// - Precondition: self is assumed to be non-zero (should be changed /// if/when this becomes API). @usableFromInline internal var _msb: Int { diff --git a/Sources/IntegerUtilities/RoundingRule.swift b/Sources/IntegerUtilities/RoundingRule.swift index 47d13c9..937ef07 100644 --- a/Sources/IntegerUtilities/RoundingRule.swift +++ b/Sources/IntegerUtilities/RoundingRule.swift @@ -60,6 +60,34 @@ public enum RoundingRule { /// Adds a uniform random value from [0, d) to the value being rounded, /// where d is the distance between the two closest representable values, /// then rounds the sum downwards. + /// + /// Unlike all the other rounding modes, this mode is _not deterministic_; + /// repeated calls to rounding operations with this mode will generally + /// produce different results. There is a tradeoff implicit in using this + /// mode: you can sacrifice _reproducible_ results to get _more accurate_ + /// results in aggregate. For a contrived but illustrative example, consider + /// the following: + /// ``` + /// let data = Array(repeating: 1, count: 100) + /// let result = data.reduce(0) { + /// $0 + $1.divided(by: 3, rounding: rule) + /// } + /// ``` + /// because 1/3 is always the same value between 0 and 1, any + /// deterministic rounding rule must produce either 0 or 100 for + /// this computation. But rounding `stochastically` will + /// produce a value close to 33. The _error_ of the computation + /// is smaller, but the result will now change between runs of the + /// program. + /// + /// For this simple case a better solution would be to add the + /// values first, and then divide. This gives a result that is both + /// reproducible _and_ accurate: + /// ``` + /// let result = data.reduce(0, +)/3 + /// ``` + /// but this isn't always possible in more sophisticated scenarios, + /// and in those cases this rounding rule may be useful. case stochastically /// If the value being rounded is representable, that value is returned. diff --git a/Sources/IntegerUtilities/SaturatingArithmetic.swift b/Sources/IntegerUtilities/SaturatingArithmetic.swift new file mode 100644 index 0000000..14aebd4 --- /dev/null +++ b/Sources/IntegerUtilities/SaturatingArithmetic.swift @@ -0,0 +1,60 @@ +//===--- SaturatingArithmetic.swift ---------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2023 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 FixedWidthInteger { + @_transparent @usableFromInline + var signExtension: Self { self &>> -1 } + + @inlinable + public func addingWithSaturation(_ other: Self) -> Self { + let (wrapped, overflow) = addingReportingOverflow(other) + if !overflow { return wrapped } + return Self.max &- signExtension + } + + @inlinable + public func subtractingWithSaturation(_ other: Self) -> Self { + let (wrapped, overflow) = subtractingReportingOverflow(other) + if !overflow { return wrapped } + return Self.max &- signExtension + } + + @inlinable + public func multipliedWithSaturation(by other: Self) -> Self { + let (high, low) = multipliedFullWidth(by: other) + let wrapped = Self(truncatingIfNeeded: low) + if high == wrapped.signExtension { return wrapped } + return Self.max &- high.signExtension + } + + @inlinable + public func shiftedWithSaturation( + leftBy count: Count, rounding rule: RoundingRule = .down + ) -> Self { + // If count is zero or negative, negate it and do a right + // shift without saturation instead, as that's easier. + guard count > 0 else { + // TODO: fixup case where 0 - count overflows + return shifted(rightBy: 0 - count, rounding: rule) + } + guard count < Self.bitWidth else { + // If count is bitWidth or greater, we always overflow + // unless self is zero. + return self == 0 ? 0 : Self.max &- signExtension + } + // Now we have 0 < count < bitWidth, so we can use a nice + // straightforward implementation; the shift overflows if + // the complementary shift doesn't match sign extension. + let wrapped = self << count + if self &>> ~count == signExtension { return wrapped } + return Self.max &- signExtension + } +}