diff --git a/Sources/IntegerUtilities/Rounding.swift b/Sources/IntegerUtilities/Rounding.swift new file mode 100644 index 0000000..adca6aa --- /dev/null +++ b/Sources/IntegerUtilities/Rounding.swift @@ -0,0 +1,139 @@ +//===--- Rounding.swift ---------------------------------------*- swift -*-===// +// +// This source file is part of the Swift Numerics open source project +// +// Copyright (c) 2021 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 +// +//===----------------------------------------------------------------------===// + +public enum RoundingRule { + case down + case up + case towardZero + case awayFromZero +// toEven + case toOdd +// toNearestOrDown +// toNearestOrUp +// toNearestOrTowardZero + case toNearestOrAwayFromZero + case toNearestOrEven +// toNearestOrOdd + case stochastic + case trap +} + +extension BinaryInteger { + public func shifted( + right count: Count, + rounding rule: RoundingRule = .down + ) -> Self { + // Easiest case: count is zero or negative, so shift is always exact; + // delegate to the normal >> operator. + if count <= 0 { return self >> count } + if count >= bitWidth { + // Note: what follows would cause an infinite loop if bitWidth <= 1. + // This will essentially never happen, but in the highly unlikely event + // that we encounter such a case, we promote to Int8, do the shift, and + // then convert back to the appropriate result type. + if bitWidth <= 1 { + return Self(Int8(self).shifted(right: count, rounding: rule)) + } + // That pathological case taken care of, we can now handle over-wide + // shifts by first shifting all but bitWidth - 1 bits with sticky + // rounding, and then shifting the remaining bitWidth - 1 bits with + // the desired rounding mode. + let count = count - Count(bitWidth - 1) + var floor = self >> count + let frac = self - (floor << count) + if frac != 0 { floor |= 1 } // insert sticky bit + return floor.shifted(right: bitWidth - 1, rounding: rule) + } + // Now we are in the happy case: 0 < count < bitWidth, which makes all + // the math to handle rounding simpler. + // + // TODO: If we were really, really careful about overflow, some of these + // could be made simpler. E.g. mathematically round up is implemented here + // via: + // + // floor = self >> count + // mask = 1 << count - 1 + // frac = self & mask + // return floor + (frac == 0 ? 0 : 1) + // + // _if_ we didn't have to worry about intermediate overflow (either because + // self is bounded away from .max or because we don't have a fixed-width + // type), then we could use the following instead: + // + // mask = 1 << count - 1 + // return (self + mask) >> count + // + // However, self + mask can overflow, e.g. if we're shifting .max by 1: + // + // mask = 1 << 1 - 1 = 1 + // self + mask = .max + 1 // uh-oh + // + // This cannot occur for arbitrary-precision numbers, so we could use + // the simpler expressions for those (but those are precisely the cases + // where performance does not matter). More interesting, we could promote + // fixed-width numbers to a wider type, preventing this intermediate + // overflow and allowing us to use the simpler expressions much of the + // time. We could also explicitly _detect_ the overflow if it happens and + // patch up the result, though this is a little bit tricky because + // addingReportingOverflow does not exist on BinaryInteger. Hence, this + // is a TODO for the future. + let mask = Magnitude(1) << count - 1 + let frac = Magnitude(truncatingIfNeeded: self) & mask + let floor = self >> count + let ceiling = floor + (frac == 0 ? 0 : 1) + switch rule { + case .down: + return floor + case .up: + return ceiling + case .towardZero: + return self > 0 ? floor : ceiling + case .awayFromZero: + return self < 0 ? floor : ceiling + case .toOdd: + return floor | (frac == 0 ? 0 : 1) + case .toNearestOrAwayFromZero: + let round = mask >> 1 + (self > 0 ? 1 : 0) + return floor + Self((round + frac) >> count) + case .toNearestOrEven: + let round = mask >> 1 + Magnitude(floor & 1) + return floor + Self((round + frac) >> count) + case .stochastic: + // TODO: it's unfortunate that we can't specify a custom random source + // for the stochastic rounding rule, but I don't see a nice way to have + // that share the API with the other rounding rules, because we'd then + // have to take the RNG in-out. The same problem applies to rounding + // with dithering. We should consider adding a stateful rounding API + // down the road to support those use cases. + // + // In theory, u01 should be Self.random(in: 0 ..< onesBit), but the + // random(in:) method does not exist on BinaryInteger. This is + // (arguably) good, though, because there's actually no reason to + // generate large amounts of randomness just to implement stochastic + // rounding for bigints; we can cap it at word-size, which is way + // more than needed to generate high-quality results. + let u01 = UInt.random(in: 0 ... .max) + if count < UInt.bitWidth { + // count is small, so u01 & mask is representable as both UInt + // and Self, regardless of what type Self actually is. + return floor + Self(((u01 & UInt(mask)) + UInt(frac)) >> count) + } + // count is large, so Self is a type larger than UInt. Do the shift + // for frac in two stages so we can do the rounding work in UInt: + let smallFrac = UInt(truncatingIfNeeded: frac >> (count - Count(UInt.bitWidth))) + let (_, carry) = smallFrac.addingReportingOverflow(u01) + return floor + (carry ? 1 : 0) + case .trap: + precondition(frac == 0, "shift was not exact.") + return floor + } + } +} diff --git a/Tests/IntegerUtilitiesTests/RoundingTests.swift b/Tests/IntegerUtilitiesTests/RoundingTests.swift new file mode 100644 index 0000000..ff5d4ec --- /dev/null +++ b/Tests/IntegerUtilitiesTests/RoundingTests.swift @@ -0,0 +1,136 @@ +//===--- RoundingTests.swift ----------------------------------*- swift -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2021 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import IntegerUtilities +import XCTest + +final class RoundingTests: XCTestCase { + + func testRoundingShift( + _ value: T, _ count: Int, rounding rule: RoundingRule + ) { + let floor = value >> count + let frac = value &- floor << count + let exact = count <= 0 || frac == 0 + let ceiling = exact ? floor : floor &+ 1 + let expected: T + switch rule { + case .down: + expected = floor + case .up: + expected = ceiling + case .towardZero: + expected = value < 0 ? ceiling : floor + case .awayFromZero: + expected = value > 0 ? ceiling : floor + case .toOdd: + expected = floor | (exact ? 0 : 1) + case .toNearestOrAwayFromZero: + if exact { expected = floor } + else { + let step = value.shifted(right: count - 2, rounding: .toOdd) + switch step & 0b11 { + case 0b01: expected = floor + case 0b10: expected = value > 0 ? ceiling : floor + case 0b11: expected = ceiling + default: preconditionFailure() + } + } + case .toNearestOrEven: + if exact { expected = floor } + else { + let step = value.shifted(right: count - 2, rounding: .toOdd) + switch step & 0b11 { + case 0b01: expected = floor + case 0b10: expected = floor & 1 == 0 ? floor : ceiling + case 0b11: expected = ceiling + default: preconditionFailure() + } + } + case .stochastic: + // Just test that it's floor if exact, otherwise either floor + // or ceiling. + if exact { expected = floor } + else { + let observed = value.shifted(right: count, rounding: rule) + if observed != floor && observed != ceiling { + print("Error found in \(T.self).shifted(right: \(count), rounding: \(rule)).") + print(" Value: \(String(value, radix: 16))") + print("Expected: \(String(floor, radix: 16)) or \(String(ceiling, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + } + return + } + case .trap: + preconditionFailure() + } + let observed = value.shifted(right: count, rounding: rule) + if observed != expected { + print("Error found in \(T.self).shifted(right: \(count), rounding: \(rule)).") + print(" Value: \(String(value, radix: 16))") + print("Expected: \(String(expected, radix: 16))") + print("Observed: \(String(observed, radix: 16))") + XCTFail() + } + } + + func testRoundingShift( + _ type: T.Type, rounding rule: RoundingRule + ) { + for count in -2*T.bitWidth ... 2*T.bitWidth { + // zero shifted by anything is always zero + XCTAssertEqual(0, (0 as T).shifted(right: count, rounding: rule)) + for _ in 0 ..< 100 { + testRoundingShift(T.random(in: .min ... .max), count, rounding: rule) + } + } + } + + func testRoundingShift() { + testRoundingShift(Int8.self, rounding: .down) + testRoundingShift(Int8.self, rounding: .up) + testRoundingShift(Int8.self, rounding: .towardZero) + testRoundingShift(Int8.self, rounding: .awayFromZero) + testRoundingShift(Int8.self, rounding: .toOdd) + testRoundingShift(Int8.self, rounding: .toNearestOrAwayFromZero) + testRoundingShift(Int8.self, rounding: .toNearestOrEven) + testRoundingShift(Int8.self, rounding: .stochastic) + + testRoundingShift(UInt8.self, rounding: .down) + testRoundingShift(UInt8.self, rounding: .up) + testRoundingShift(UInt8.self, rounding: .towardZero) + testRoundingShift(UInt8.self, rounding: .awayFromZero) + testRoundingShift(UInt8.self, rounding: .toOdd) + testRoundingShift(UInt8.self, rounding: .toNearestOrAwayFromZero) + testRoundingShift(UInt8.self, rounding: .toNearestOrEven) + testRoundingShift(UInt8.self, rounding: .stochastic) + + testRoundingShift(Int.self, rounding: .down) + testRoundingShift(Int.self, rounding: .up) + testRoundingShift(Int.self, rounding: .towardZero) + testRoundingShift(Int.self, rounding: .awayFromZero) + testRoundingShift(Int.self, rounding: .toOdd) + testRoundingShift(Int.self, rounding: .toNearestOrAwayFromZero) + testRoundingShift(Int.self, rounding: .toNearestOrEven) + testRoundingShift(Int.self, rounding: .stochastic) + + testRoundingShift(UInt.self, rounding: .down) + testRoundingShift(UInt.self, rounding: .up) + testRoundingShift(UInt.self, rounding: .towardZero) + testRoundingShift(UInt.self, rounding: .awayFromZero) + testRoundingShift(UInt.self, rounding: .toOdd) + testRoundingShift(UInt.self, rounding: .toNearestOrAwayFromZero) + testRoundingShift(UInt.self, rounding: .toNearestOrEven) + testRoundingShift(UInt.self, rounding: .stochastic) + } +}