mirror of
https://github.com/apple/swift-numerics
synced 2026-11-29 05:24:24 +00:00
First pass.
This commit is contained in:
1 parent
93e5499e54
commit
7953ef315a
4 files changed
+94
-4
No files matched your search
@@ -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})
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Count: BinaryInteger>(
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user