diff --git a/Sources/IntegerUtilities/DivideWithRounding.swift b/Sources/IntegerUtilities/DivideWithRounding.swift index c0cf0a6..2c67e65 100644 --- a/Sources/IntegerUtilities/DivideWithRounding.swift +++ b/Sources/IntegerUtilities/DivideWithRounding.swift @@ -64,44 +64,58 @@ extension BinaryInteger { // disagree, we have to adjust q downward and r to match. if other.signum() != r.signum() { return q-1 } return q + case .up: // For rounding up, we want to have r have the opposite sign of // other; if not, we adjust q upward and r to match. if other.signum() == r.signum() { return q+1 } return q + case .towardZero: // This is exactly what the `/` operator did for us. return q - case .toOdd: - // If q is already odd, we're done. - if q._lowWord & 1 == 1 { return q } - // Otherwise, q is even but inexact; it was originally rounded toward - // zero, so rounding away from zero instead will make it odd. - fallthrough + case .awayFromZero: - // To round away from zero, we apply the adjustments for both down - // and up. - if other.signum() != r.signum() { return q-1 } - return q+1 - case .toNearestOrAwayFromZero: - // For round to nearest or away, the condition we want to satisfy is - // |r| <= |other/2|, with sign(q) != sign(r) when equality holds. + break + + case .toNearestOrDown: + if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) || + 2*r.magnitude == other.magnitude && other.signum() != r.signum() { + break + } + return q + + case .toNearestOrUp: + if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) || + 2*r.magnitude == other.magnitude && other.signum() == r.signum() { + break + } + return q + + case .toNearestOrZero: + if r.magnitude <= other.magnitude.shifted(rightBy: 1, rounding: .down) { + return q + } + // Otherwise, round q away from zero. + + case .toNearestOrAway: if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) { return q } - // The (q,r) we have does not satisfy the to nearest or away condition; - // round away from zero to choose the other representative of (q, r). - if other.signum() != r.signum() { return q-1 } - return q+1 + case .toNearestOrEven: - // For round to nearest or away, the condition we want to satisfy is - // |r| <= |other/2|, with q even when equality holds. - if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) || - 2*r.magnitude == other.magnitude && q._lowWord & 1 == 1 { - if (other > 0) != (r > 0) { return q-1 } - return q+1 + // First guarantee that |r| <= |other/2|; if not we have to round away + // instead, so break to do that. + if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) || + 2*r.magnitude == other.magnitude && !q.isMultiple(of: 2) { + break } return q + + case .toOdd: + // If q is already odd, we have the correct result. + if q._lowWord & 1 == 1 { return q } + case .stochastically: var qhi: UInt64 var rhi: UInt64 @@ -121,9 +135,13 @@ extension BinaryInteger { return q+1 } return q + case .requireExact: preconditionFailure("Division was not exact.") } + + // We didn't have the right result, so round q away from zero. + return other.signum() == r.signum() ? q+1 : q-1 } // TODO: make this API and make it possible to implement more efficiently. @@ -221,46 +239,70 @@ extension SignedInteger { // For rounding down, we want to have r match the sign of other // rather than self; this means that if the signs of r and other // disagree, we have to adjust q downward and r to match. - if other.signum() != r.signum() { return (q-1, r+other) } - return (q, r) + return other.signum() == r.signum() ? (q, r) : (q-1, r+other) + case .up: // For rounding up, we want to have r have the opposite sign of // other; if not, we adjust q upward and r to match. - if other.signum() == r.signum() { return (q+1, r-other) } - return (q, r) + return other.signum() == r.signum() ? (q+1, r-other) : (q, r) + case .towardZero: // This is exactly what the `/` operator did for us. return (q, r) - case .toOdd: - // If q is already odd, we're done. - if q._lowWord & 1 == 1 { return (q, r) } - // Otherwise, q is even but inexact; it was originally rounded toward - // zero, so rounding away from zero instead will make it odd. - fallthrough + case .awayFromZero: - // To round away from zero, we apply the adjustments for both down - // and up. - if other.signum() != r.signum() { return (q-1, r+other) } - return (q+1, r-other) - case .toNearestOrAwayFromZero: - // For round to nearest or away, the condition we want to satisfy is - // |r| <= |other/2|, with sign(q) != sign(r) when equality holds. - if r.magnitude < other.magnitude.shifted(rightBy: 1, rounding: .up) { + break + + case .toNearestOrDown: + // If |r| < |other/2|, we already rounded q to nearest. If the are + // equal and q is negative, then we already broke the tie in the right + // direction. However, we don't have access to the before-rounding q, + // which may have rounded up to zero, losing the sign information, so + // we have to look at other and r instead. + if 2*r.magnitude < other.magnitude || + 2*r.magnitude == other.magnitude && other.signum() == r.signum() { return (q, r) } - // The (q,r) we have does not satisfy the to nearest or away condition; - // round away from zero to choose the other representative of (q, r). - if other.signum() != r.signum() { return (q-1, r+other) } - return (q+1, r-other) - case .toNearestOrEven: - // For round to nearest or away, the condition we want to satisfy is - // |r| <= |other/2|, with q even when equality holds. - if r.magnitude > other.magnitude.shifted(rightBy: 1, rounding: .down) || - 2*r.magnitude == other.magnitude && q._lowWord & 1 == 1 { - if (other > 0) != (r > 0) { return (q-1, r+other) } - return (q+1, r-other) + + case .toNearestOrUp: + // If |r| < |other/2|, we already rounded q to nearest. If the are + // equal and q is non-negative, then we already broke the tie in the + // right direction. + if 2*r.magnitude < other.magnitude || + 2*r.magnitude == other.magnitude && other.signum() != r.signum() { + return (q, r) } - return (q, r) + + case .toNearestOrZero: + // Check first if |r| <= |other/2|. If this holds, we have already + // rounded q correctly. Because we're working with magnitudes, we can + // safely compute 2r without worrying about overflow, even for fixed- + // width types, because r cannot be .min (because |r| < |other| by + // construction). + if 2*r.magnitude <= other.magnitude { + return (q, r) + } + + case .toNearestOrAway: + // Check first if |r| < |other/2|. If this holds, we already rounded + // q to nearest. + if 2*r.magnitude < other.magnitude { + return (q, r) + } + + case .toNearestOrEven: + // If |r| < |other/2|, we already rounded q to nearest. If the are + // equal and q is even, then we already broke the tie in the right + // direction. + if 2*r.magnitude < other.magnitude || + 2*r.magnitude == other.magnitude && q.isMultiple(of: 2) { + return (q, r) + } + + case .toOdd: + // If q is already odd, we have the correct result. + if q._lowWord & 1 == 1 { return (q, r) } + case .stochastically: var qhi: UInt64 var rhi: UInt64 @@ -280,9 +322,14 @@ extension SignedInteger { return (q+1, r-other) } return (q, r) + case .requireExact: preconditionFailure("Division was not exact.") } + + // Fallthrough behavior is to round q away from zero and adjust r to + // match. + return other.signum() == r.signum() ? (q+1, r-other) : (q-1, r+other) } } diff --git a/Sources/IntegerUtilities/RoundingRule.swift b/Sources/IntegerUtilities/RoundingRule.swift index 687ce14..0dc9d83 100644 --- a/Sources/IntegerUtilities/RoundingRule.swift +++ b/Sources/IntegerUtilities/RoundingRule.swift @@ -2,13 +2,21 @@ // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2021-2024 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 // //===----------------------------------------------------------------------===// +// 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 either the rule in-out or have an additional RNG/state +// parameter. The same problem applies to rounding with dithering and +// any other stateful rounding method. We should consider adding a +// stateful rounding API down the road to support those use cases. + /// A rule that defines how to select one of the two representable results /// closest to a given value. /// @@ -17,38 +25,56 @@ /// /// Examples using rounding to integer to illustrate the various options: /// ``` +/// Directed rounding rules +/// /// value | down | up | towardZero | awayFromZero | /// =======+==============+==============+==============+==============+ -/// 1.5 | 1 | 2 | 1 | 2 | +/// -1.5 | -2 | -1 | -1 | -2 | /// -------+--------------+--------------+--------------+--------------+ /// -0.5 | -1 | 0 | 0 | -1 | /// -------+--------------+--------------+--------------+--------------+ -/// 0.3 | 0 | 1 | 0 | 1 | +/// 0.5 | 0 | 1 | 0 | 1 | /// -------+--------------+--------------+--------------+--------------+ -/// 2 | 2 | 2 | 2 | 2 | +/// 0.7 | 0 | 1 | 0 | 1 | +/// -------+--------------+--------------+--------------+--------------+ +/// 1.2 | 1 | 2 | 1 | 2 | +/// -------+--------------+--------------+--------------+--------------+ +/// 2.0 | 2 | 2 | 2 | 2 | /// -------+--------------+--------------+--------------+--------------+ /// -/// value | toOdd | toNearestOrAwayFromZero | toNearestOrEven | -/// =======+==============+=========================+==================+ -/// 1.5 | 1 | 2 | 2 | -/// -------+--------------+-------------------------+------------------+ -/// -0.5 | -1 | -1 | 0 | -/// -------+--------------+-------------------------+------------------+ -/// 0.3 | 1 | 0 | 0 | -/// -------+--------------+-------------------------+------------------+ -/// 2 | 2 | 2 | 2 | -/// -------+--------------+-------------------------+------------------+ +/// toNearestOr... rounding rules /// -/// value | stochastically | requireExact | -/// =======+=======================+================+ -/// 1.5 | 50% 1, 50% 2 | trap | -/// -------+-----------------------+----------------+ -/// -0.5 | 50% -1, 50% 0 | trap | -/// -------+-----------------------+----------------+ -/// 0.3 | 70% 0, 30% 1 | trap | -/// -------+-----------------------+----------------+ -/// 2 | 2 | 2 | -/// -------+-----------------------+----------------+ +/// value | orDown | orUp | orZero | orAway | orEven | +/// =======+==========+==========+==========+==========+==========+ +/// -1.5 | -2 | -1 | -1 | -2 | -2 | +/// -------+----------+----------+----------+----------+----------+ +/// -0.5 | -1 | 0 | 0 | -1 | 0 | +/// -------+----------+----------+----------+----------+----------+ +/// 0.5 | 0 | 1 | 0 | 1 | 0 | +/// -------+----------+----------+----------+----------+----------+ +/// 0.7 | 1 | 1 | 1 | 1 | 1 | +/// -------+----------+----------+----------+----------+----------+ +/// 1.2 | 1 | 1 | 1 | 1 | 1 | +/// -------+----------+----------+----------+----------+----------+ +/// 2.0 | 2 | 2 | 2 | 2 | 2 | +/// -------+----------+----------+----------+----------+----------+ +/// +/// Specialized rounding rules +/// +/// value | toOdd | stochastically | requireExact | +/// =======+==============+=======================+================+ +/// -1.5 | -1 | 50% -2, 50% -1 | trap | +/// -------+--------------+-----------------------+----------------+ +/// -0.5 | -1 | 50% -1, 50% 0 | trap | +/// -------+--------------+-----------------------+----------------+ +/// 0.5 | 1 | 50% 0, 50% 1 | trap | +/// -------+--------------+-----------------------+----------------+ +/// 0.7 | 1 | 30% 0, 70% 1 | trap | +/// -------+--------------+-----------------------+----------------+ +/// 1.2 | 1 | 80% 1, 20% 2 | trap | +/// -------+--------------+-----------------------+----------------+ +/// 2.0 | 2 | 2 | 2 | +/// -------+--------------+-----------------------+----------------+ /// ``` public enum RoundingRule { /// Produces the closest representable value that is less than or equal @@ -113,18 +139,54 @@ public enum RoundingRule { /// even though 2 is even, because 4/2 is exactly 2 and no rounding occurs. case toOdd + /// Produces the representable value that is closest to the value being + /// rounded. If two values are equally close, the one that is less than + /// the value being rounded is chosen. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toNearestOrDown)` + /// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2. + /// + /// - `5.shifted(rightBy: 1, rounding: .toNearestOrDown)` is `2`, + /// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is less. + case toNearestOrDown + + /// Produces the representable value that is closest to the value being + /// rounded. If two values are equally close, the one that is greater than + /// the value being rounded is chosen. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toNearestOrUp)` + /// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2. + /// + /// - `5.shifted(rightBy: 1, rounding: .toNearestOrUp)` is `3`, + /// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is greater. + case toNearestOrUp + + /// Produces the representable value that is closest to the value being + /// rounded. If two values are equally close, the one that has smaller + /// magnitude is returned. + /// + /// Examples: + /// - `(-4).divided(by: 3, rounding: .toNearestOrZero)` + /// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2. + /// + /// - `5.shifted(rightBy: 1, rounding: .toNearestOrZero)` is `3`, + /// because 5/2 = 2.5 is equally close to 2 and 3, and 2 is closer to zero. + case toNearestOrZero + /// Produces the representable value that is closest to the value being /// rounded. If two values are equally close, the one that has greater /// magnitude is returned. /// /// Examples: - /// - `(-4).divided(by: 3, rounding: .toNearestOrAwayFromZero)` + /// - `(-4).divided(by: 3, rounding: .toNearestOrAway)` /// is `-1`, because –4/3 = –1.3̅ is closer to –1 than it is to –2. /// - /// - `5.shifted(rightBy: 1, rounding: .toNearestOrAwayFromZero)` is `3`, + /// - `5.shifted(rightBy: 1, rounding: .toNearestOrAway)` is `3`, /// because 5/2 = 2.5 is equally close to 2 and 3, and 3 is further away /// from zero. - case toNearestOrAwayFromZero + case toNearestOrAway /// Produces the representable value that is closest to the value being /// rounded. If two values are equally close, the one whose least @@ -185,3 +247,14 @@ public enum RoundingRule { /// because –4/3 = –1.3̅ is not an integer. case requireExact } + +extension RoundingRule { + /// Produces the representable value that is closest to the value being + /// rounded. If two values are equally close, the one that has greater + /// magnitude is returned. + /// + /// > Deprecated: Use `.toNearestOrAway` instead. + @inlinable + @available(*, deprecated, renamed: "toNearestOrAway") + static var toNearestOrAwayFromZero: Self { .toNearestOrAway } +} diff --git a/Sources/IntegerUtilities/SaturatingArithmetic.swift b/Sources/IntegerUtilities/SaturatingArithmetic.swift index 2d933f8..7c00160 100644 --- a/Sources/IntegerUtilities/SaturatingArithmetic.swift +++ b/Sources/IntegerUtilities/SaturatingArithmetic.swift @@ -95,7 +95,7 @@ extension FixedWidthInteger { return Self.max &- high.signbit } - /// Bitwise left with rounding and saturation. + /// Bitwise left shift with rounding and saturation. /// /// `self` multiplied by the rational number 2^(`count`), saturated to the /// range `Self.min ... Self.max`, and rounded according to `rule`. @@ -154,8 +154,8 @@ extension FixedWidthInteger { /// shifts with examples. /// /// - Parameters: - /// - leftBy count: the number of bits to shift by. If positive, this is a left-shift, - /// and if negative a right shift. + /// - leftBy count: the number of bits to shift by. If positive, this is a + /// left-shift, and if negative a right shift. /// - rounding rule: the direction in which to round if `count` is negative. @_transparent public func shiftedWithSaturation( diff --git a/Sources/IntegerUtilities/ShiftWithRounding.swift b/Sources/IntegerUtilities/ShiftWithRounding.swift index d03bbae..0493d04 100644 --- a/Sources/IntegerUtilities/ShiftWithRounding.swift +++ b/Sources/IntegerUtilities/ShiftWithRounding.swift @@ -105,6 +105,7 @@ extension BinaryInteger { let lost = Magnitude(truncatingIfNeeded: self) & mask let floor = self >> count let ceiling = floor + (lost == 0 ? 0 : 1) + let half: Magnitude = (1 as Magnitude) << (count &- 1) switch rule { case .down: return floor @@ -114,22 +115,22 @@ extension BinaryInteger { return self > 0 ? floor : ceiling case .awayFromZero: return self < 0 ? floor : ceiling - case .toOdd: - return floor | (lost == 0 ? 0 : 1) - case .toNearestOrAwayFromZero: - let round = mask >> 1 + (self > 0 ? 1 : 0) + case .toNearestOrDown: + return floor + Self((lost + (half - 1)) >> count) + case .toNearestOrUp: + return floor + Self((lost + half) >> count) + case .toNearestOrZero: + let round = half - (self < 0 ? 0 : 1) + return floor + Self((round + lost) >> count) + case .toNearestOrAway: + let round = half - (self > 0 ? 0 : 1) return floor + Self((round + lost) >> count) case .toNearestOrEven: let round = mask >> 1 + Magnitude(floor & 1) return floor + Self((round + lost) >> count) + case .toOdd: + return floor | (lost == 0 ? 0 : 1) case .stochastically: - // TODO: it's unfortunate that we can't specify a custom random source - // for the stochastically 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 diff --git a/Tests/IntegerUtilitiesTests/DivideTests.swift b/Tests/IntegerUtilitiesTests/DivideTests.swift index a34e7a3..71adccc 100644 --- a/Tests/IntegerUtilitiesTests/DivideTests.swift +++ b/Tests/IntegerUtilitiesTests/DivideTests.swift @@ -25,14 +25,14 @@ final class IntegerUtilitiesDivideTests: XCTestCase { let ref = a - q*b1 - q*b2 if r != ref { XCTFail(""" - \(a).divided(by: \(b), rounding: .down) failed the division rule. + \(a).divided(by: \(b)) failed the division rule. a - qb was \(ref), but r is \(r). """) return false } if r.magnitude >= b.magnitude { XCTFail(""" - \(a).divided(by: \(b), rounding: .down) failed check on r. + \(a).divided(by: \(b)) failed check on r. |remainder| must be smaller than |divisor|, but was \(r). """) return false @@ -46,6 +46,15 @@ final class IntegerUtilitiesDivideTests: XCTestCase { // Skip any SignedInt.min / -1 cases, because those will trap. if a == .min && b == -1 { continue } let (q, r) = a.divided(by: b, rounding: .down) + let justq = a.divided(by: b, rounding: .down) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .down) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } if divisionRuleHolds(a, b, q, r) { // We know a = bq + r with |r| < |b|. Now validate sign(r) == sign(b). guard r == 0 || r.signum() == b.signum() else { @@ -66,6 +75,15 @@ final class IntegerUtilitiesDivideTests: XCTestCase { // Skip any SignedInt.min / -1 cases, because those will trap. if a == .min && b == -1 { continue } let (q, r) = a.divided(by: b, rounding: .up) + let justq = a.divided(by: b, rounding: .up) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .up) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } if divisionRuleHolds(a, b, q, r) { // We know a = bq + r with |r| < |b|. Now validate sign(r) != sign(b). guard r == 0 || r.signum() != b.signum() else { @@ -86,6 +104,15 @@ final class IntegerUtilitiesDivideTests: XCTestCase { // Skip any SignedInt.min / -1 cases, because those will trap. if a == .min && b == -1 { continue } let (q, r) = a.divided(by: b, rounding: .towardZero) + let justq = a.divided(by: b, rounding: .towardZero) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .towardZero) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } if divisionRuleHolds(a, b, q, r) { // We know a = bq + r with |r| < |b|. Now validate sign(r) == sign(a). guard r == 0 || r.signum() == a.signum() else { @@ -106,6 +133,15 @@ final class IntegerUtilitiesDivideTests: XCTestCase { // Skip any SignedInt.min / -1 cases, because those will trap. if a == .min && b == -1 { continue } let (q, r) = a.divided(by: b, rounding: .awayFromZero) + let justq = a.divided(by: b, rounding: .awayFromZero) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .awayFromZero) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } if divisionRuleHolds(a, b, q, r) { // We know a = bq + r with |r| < |b|. Now validate sign(r) != sign(a). guard r == 0 || r.signum() != a.signum() else { @@ -120,19 +156,111 @@ final class IntegerUtilitiesDivideTests: XCTestCase { } } - func testDivideToOdd(_ values: [T]) { + func testDivideToNearestOrDown(_ values: [T]) { for a in values { for b in values where b != 0 { // Skip any SignedInt.min / -1 cases, because those will trap. if a == .min && b == -1 { continue } - let (q, r) = a.divided(by: b, rounding: .toOdd) + let (q, r) = a.divided(by: b, rounding: .toNearestOrDown) + let justq = a.divided(by: b, rounding: .toNearestOrDown) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrDown) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } + + XCTAssertEqual(q, justq) if divisionRuleHolds(a, b, q, r) { - // We know a = bq + r with |r| < |b|. Now validate q is odd if r is - // non-zero. - guard r == 0 || q & 1 == 1 else { + // We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2 + // with equality only if q rounded down. + if 2*r.magnitude > b.magnitude { XCTFail(""" - \(a).divided(by: \(b), rounding: .toOdd) failed check: - quotient must be odd if remainder is non-zero, but quotient was \(q) and remainder was \(r). + \(a).divided(by: \(b), rounding: .toNearestOrDown) failed check: + |remainder| must be less than or equal to |divisor|/2, but remainder was \(r). + """) + return + } + if 2*r.magnitude == b.magnitude && r.signum() != b.signum() { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrDown) failed check: + If |remainder| equals |divisor|/2, remainder must have same sign as divisor, but was \(r). + """) + return + } + } + } + } + } + + func testDivideToNearestOrUp(_ values: [T]) { + for a in values { + for b in values where b != 0 { + // Skip any SignedInt.min / -1 cases, because those will trap. + if a == .min && b == -1 { continue } + let (q, r) = a.divided(by: b, rounding: .toNearestOrUp) + let justq = a.divided(by: b, rounding: .toNearestOrUp) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrUp) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } + if divisionRuleHolds(a, b, q, r) { + // We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2 + // with equality only if q rounded up. + if 2*r.magnitude > b.magnitude { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrUp) failed check: + |remainder| must be less than or equal to |divisor|/2, but remainder was \(r). + """) + return + } + if 2*r.magnitude == b.magnitude && r.signum() == b.signum() { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrUp) failed check: + If |remainder| equals |divisor|/2, remainder must have opposite sign of divisor, but was \(r). + """) + return + } + } + } + } + } + + func testDivideToNearestOrZero(_ values: [T]) { + for a in values { + for b in values where b != 0 { + // Skip any SignedInt.min / -1 cases, because those will trap. + if a == .min && b == -1 { continue } + let (q, r) = a.divided(by: b, rounding: .toNearestOrZero) + let justq = a.divided(by: b, rounding: .toNearestOrZero) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrZero) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } + if divisionRuleHolds(a, b, q, r) { + // We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2 + // with equality only if sign(r) == sign(a). + if 2*r.magnitude > b.magnitude { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrZero) failed check: + |remainder| must be less than or equal to |divisor|/2, but remainder was \(r). + """) + return + } + if 2*r.magnitude == b.magnitude && r.signum() != a.signum() { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrZero) failed check: + If |remainder| equals |divisor|/2, remainder must match sign of dividend, but was \(r). """) return } @@ -146,20 +274,29 @@ final class IntegerUtilitiesDivideTests: XCTestCase { for b in values where b != 0 { // Skip any SignedInt.min / -1 cases, because those will trap. if a == .min && b == -1 { continue } - let (q, r) = a.divided(by: b, rounding: .toNearestOrAwayFromZero) + let (q, r) = a.divided(by: b, rounding: .toNearestOrAway) + let justq = a.divided(by: b, rounding: .toNearestOrAway) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrAway) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } if divisionRuleHolds(a, b, q, r) { // We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2 // with equality only if sign(r) != sign(a). if 2*r.magnitude > b.magnitude { XCTFail(""" - \(a).divided(by: \(b), rounding: .toNearestOrAwayFromZero) failed check: + \(a).divided(by: \(b), rounding: .toNearestOrAway) failed check: |remainder| must be less than or equal to |divisor|/2, but remainder was \(r). """) return } if 2*r.magnitude == b.magnitude && r.signum() == a.signum() { XCTFail(""" - \(a).divided(by: \(b), rounding: .toNearestOrAwayFromZero) failed check: + \(a).divided(by: \(b), rounding: .toNearestOrAway) failed check: If |remainder| equals |divisor|/2, remainder must oppose sign of dividend, but was \(r). """) return @@ -175,9 +312,18 @@ final class IntegerUtilitiesDivideTests: XCTestCase { // Skip any SignedInt.min / -1 cases, because those will trap. if a == .min && b == -1 { continue } let (q, r) = a.divided(by: b, rounding: .toNearestOrEven) + let justq = a.divided(by: b, rounding: .toNearestOrEven) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toNearestOrEven) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } if divisionRuleHolds(a, b, q, r) { // We know a = bq + r with |r| < |b|. Now check |r| <= |b|/2 - // with equality only if sign(r) != sign(a). + // with equality only if q is even. if 2*r.magnitude > b.magnitude { XCTFail(""" \(a).divided(by: \(b), rounding: .toNearestOrEven) failed check: @@ -197,6 +343,36 @@ final class IntegerUtilitiesDivideTests: XCTestCase { } } + func testDivideToOdd(_ values: [T]) { + for a in values { + for b in values where b != 0 { + // Skip any SignedInt.min / -1 cases, because those will trap. + if a == .min && b == -1 { continue } + let (q, r) = a.divided(by: b, rounding: .toOdd) + let justq = a.divided(by: b, rounding: .toOdd) + if q != justq { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toOdd) failed check: + BinaryInteger overload did not produce the same quotient as SignedInteger. + BinaryInteger result was \(justq), but SignedInteger was \(q). + """) + return + } + if divisionRuleHolds(a, b, q, r) { + // We know a = bq + r with |r| < |b|. Now validate q is odd if r is + // non-zero. + guard r == 0 || q & 1 == 1 else { + XCTFail(""" + \(a).divided(by: \(b), rounding: .toOdd) failed check: + quotient must be odd if remainder is non-zero, but quotient was \(q) and remainder was \(r). + """) + return + } + } + } + } + } + func testDivideStochastic(_ values: [T]) { for a in values { for b in values where b != 0 { @@ -229,9 +405,12 @@ final class IntegerUtilitiesDivideTests: XCTestCase { testDivideUp(values) testDivideTowardZero(values) testDivideAwayFromZero(values) - testDivideToOdd(values) + testDivideToNearestOrDown(values) + testDivideToNearestOrUp(values) + testDivideToNearestOrZero(values) testDivideToNearestOrAway(values) testDivideToNearestOrEven(values) + testDivideToOdd(values) testDivideStochastic(values) testDivideExact(values) } @@ -247,9 +426,12 @@ final class IntegerUtilitiesDivideTests: XCTestCase { testDivideUp(values) testDivideTowardZero(values) testDivideAwayFromZero(values) - testDivideToOdd(values) + testDivideToNearestOrDown(values) + testDivideToNearestOrUp(values) + testDivideToNearestOrZero(values) testDivideToNearestOrAway(values) testDivideToNearestOrEven(values) + testDivideToOdd(values) testDivideStochastic(values) testDivideExact(values) } @@ -275,9 +457,50 @@ final class IntegerUtilitiesDivideTests: XCTestCase { divideUInt8(a, b, rounding: .up) divideUInt8(a, b, rounding: .towardZero) divideUInt8(a, b, rounding: .awayFromZero) - divideUInt8(a, b, rounding: .toOdd) - divideUInt8(a, b, rounding: .toNearestOrAwayFromZero) + divideUInt8(a, b, rounding: .toNearestOrDown) + divideUInt8(a, b, rounding: .toNearestOrUp) + divideUInt8(a, b, rounding: .toNearestOrZero) + divideUInt8(a, b, rounding: .toNearestOrAway) divideUInt8(a, b, rounding: .toNearestOrEven) + divideUInt8(a, b, rounding: .toOdd) + } + } + } + + @available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *) + func divideUInt64(_ a: UInt64, _ b: UInt64, rounding rule: RoundingRule) { + let expected = UInt64(Int128(a).divided(by: Int128(b), rounding: rule).quotient) + let observed = a.divided(by: b, rounding: rule) + guard expected == observed else { + XCTFail(""" + \(a).divided(by: \(b), rounding: \(rule)) did not match expected result: + Computed with Int128: \(expected) + Computed with UInt64: \(observed) + """) + return + } + } + + @available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *) + func testDivideUInt64() { + var values = [UInt64](repeating: 0, count: 64) + for i in 0 ..< values.count { + while values[i] == 0 { + values[i] = .random(in: .min ... .max) + } + } + for a in values { + for b in values where b != 0 { + divideUInt64(a, b, rounding: .down) + divideUInt64(a, b, rounding: .up) + divideUInt64(a, b, rounding: .towardZero) + divideUInt64(a, b, rounding: .awayFromZero) + divideUInt64(a, b, rounding: .toNearestOrDown) + divideUInt64(a, b, rounding: .toNearestOrUp) + divideUInt64(a, b, rounding: .toNearestOrZero) + divideUInt64(a, b, rounding: .toNearestOrAway) + divideUInt64(a, b, rounding: .toNearestOrEven) + divideUInt64(a, b, rounding: .toOdd) } } } diff --git a/Tests/IntegerUtilitiesTests/DoubleWidthTests.swift b/Tests/IntegerUtilitiesTests/DoubleWidthTests.swift index a0714b7..de073f5 100644 --- a/Tests/IntegerUtilitiesTests/DoubleWidthTests.swift +++ b/Tests/IntegerUtilitiesTests/DoubleWidthTests.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2017-2021 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2017-2024 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 diff --git a/Tests/IntegerUtilitiesTests/ShiftTests.swift b/Tests/IntegerUtilitiesTests/ShiftTests.swift index 97e0b65..2387082 100644 --- a/Tests/IntegerUtilitiesTests/ShiftTests.swift +++ b/Tests/IntegerUtilitiesTests/ShiftTests.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Numerics open source project // -// Copyright (c) 2021 Apple Inc. and the Swift Numerics project authors +// Copyright (c) 2021-2024 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 @@ -24,20 +24,44 @@ final class IntegerUtilitiesShiftTests: XCTestCase { let exact = count <= 0 || lost == 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 { + if exact { expected = floor } + else { + 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 .toNearestOrDown: + let step = value.shifted(rightBy: count - 2, rounding: .toOdd) + switch step & 0b11 { + case 0b01: expected = floor + case 0b10: expected = floor + case 0b11: expected = ceiling + default: preconditionFailure() + } + case .toNearestOrUp: + let step = value.shifted(rightBy: count - 2, rounding: .toOdd) + switch step & 0b11 { + case 0b01: expected = floor + case 0b10: expected = ceiling + case 0b11: expected = ceiling + default: preconditionFailure() + } + case .toNearestOrZero: + let step = value.shifted(rightBy: count - 2, rounding: .toOdd) + switch step & 0b11 { + case 0b01: expected = floor + case 0b10: expected = value > 0 ? floor : ceiling + case 0b11: expected = ceiling + default: preconditionFailure() + } + case .toNearestOrAway: let step = value.shifted(rightBy: count - 2, rounding: .toOdd) switch step & 0b11 { case 0b01: expected = floor @@ -45,10 +69,7 @@ final class IntegerUtilitiesShiftTests: XCTestCase { case 0b11: expected = ceiling default: preconditionFailure() } - } - case .toNearestOrEven: - if exact { expected = floor } - else { + case .toNearestOrEven: let step = value.shifted(rightBy: count - 2, rounding: .toOdd) switch step & 0b11 { case 0b01: expected = floor @@ -56,142 +77,181 @@ final class IntegerUtilitiesShiftTests: XCTestCase { case 0b11: expected = ceiling default: preconditionFailure() } - } - case .stochastically: - // Just test that it's floor if exact, otherwise either floor - // or ceiling. - if exact { expected = floor } - else { + case .stochastically: + // Just test that it's floor if exact, otherwise either floor + // or ceiling. let observed = value.shifted(rightBy: count, rounding: rule) if observed != floor && observed != ceiling { print("Error found in \(T.self).shifted(rightBy: \(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))") + print(" Value: \(String(value, radix: 2))") + print("Expected: \(String(floor, radix: 2)) or \(String(ceiling, radix: 2))") + print("Observed: \(String(observed, radix: 2))") XCTFail() } return + case .requireExact: + preconditionFailure() + } + let observed = value.shifted(rightBy: count, rounding: rule) + if observed != expected { + print("Error found in \(T.self).shifted(rightBy: \(count), rounding: \(rule)).") + print(" Value: \(String(value, radix: 2))") + print("Expected: \(String(expected, radix: 2))") + print("Observed: \(String(observed, radix: 2))") + XCTFail() } - case .requireExact: - preconditionFailure() - } - let observed = value.shifted(rightBy: count, rounding: rule) - if observed != expected { - print("Error found in \(T.self).shifted(rightBy: \(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(rightBy: count, rounding: rule)) - for _ in 0 ..< 100 { + + 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(rightBy: count, rounding: rule)) + for _ in 0 ..< 100 { + testRoundingShift(T.random(in: .min ... .max), count, rounding: rule) + } + } + + for count in Int8.min ... .max { testRoundingShift(T.random(in: .min ... .max), count, rounding: rule) } } - for count in Int8.min ... .max { - testRoundingShift(T.random(in: .min ... .max), count, rounding: rule) - } - } - - func testRoundingShifts() { - 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: .stochastically) - - 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: .stochastically) - - 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: .stochastically) - - 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: .stochastically) - } - - // Stochastic rounding doesn't have a deterministic "expected" answer, - // but we know that the result must be either the floor or the ceiling. - // The above tests ensure that, but that's not a very strong guarantee; - // an implementation could just implement it as self >> count and pass - // that test. - // - // Here we round the _same_ value many times, compute the average, and - // check that it is acceptably close to the exact expected value; simple - // use of any deterministic rounding rule will not achieve this. - func testStochasticAverage(_ value: T) { - var fails = 0 - for count in 1 ... T.bitWidth { - let sum = (0..<256).reduce(into: DoubleWidth.zero) { sum, _ in - let rounded = value.shifted(rightBy: count, rounding: .stochastically) - sum += DoubleWidth(rounded) + func testRoundingShifts() { + testRoundingShift(Int8.self, rounding: .down) + testRoundingShift(Int8.self, rounding: .up) + testRoundingShift(Int8.self, rounding: .towardZero) + testRoundingShift(Int8.self, rounding: .awayFromZero) + testRoundingShift(Int8.self, rounding: .toNearestOrUp) + testRoundingShift(Int8.self, rounding: .toNearestOrDown) + testRoundingShift(Int8.self, rounding: .toNearestOrZero) + testRoundingShift(Int8.self, rounding: .toNearestOrAway) + testRoundingShift(Int8.self, rounding: .toNearestOrEven) + testRoundingShift(Int8.self, rounding: .toOdd) + testRoundingShift(Int8.self, rounding: .stochastically) + + testRoundingShift(UInt8.self, rounding: .down) + testRoundingShift(UInt8.self, rounding: .up) + testRoundingShift(UInt8.self, rounding: .towardZero) + testRoundingShift(UInt8.self, rounding: .awayFromZero) + testRoundingShift(UInt8.self, rounding: .toNearestOrUp) + testRoundingShift(UInt8.self, rounding: .toNearestOrDown) + testRoundingShift(UInt8.self, rounding: .toNearestOrZero) + testRoundingShift(UInt8.self, rounding: .toNearestOrAway) + testRoundingShift(UInt8.self, rounding: .toNearestOrEven) + testRoundingShift(UInt8.self, rounding: .toOdd) + testRoundingShift(UInt8.self, rounding: .stochastically) + + testRoundingShift(Int.self, rounding: .down) + testRoundingShift(Int.self, rounding: .up) + testRoundingShift(Int.self, rounding: .towardZero) + testRoundingShift(Int.self, rounding: .awayFromZero) + testRoundingShift(Int.self, rounding: .toNearestOrUp) + testRoundingShift(Int.self, rounding: .toNearestOrDown) + testRoundingShift(Int.self, rounding: .toNearestOrZero) + testRoundingShift(Int.self, rounding: .toNearestOrAway) + testRoundingShift(Int.self, rounding: .toNearestOrEven) + testRoundingShift(Int.self, rounding: .toOdd) + testRoundingShift(Int.self, rounding: .stochastically) + + testRoundingShift(UInt.self, rounding: .down) + testRoundingShift(UInt.self, rounding: .up) + testRoundingShift(UInt.self, rounding: .towardZero) + testRoundingShift(UInt.self, rounding: .awayFromZero) + testRoundingShift(UInt.self, rounding: .toNearestOrUp) + testRoundingShift(UInt.self, rounding: .toNearestOrDown) + testRoundingShift(UInt.self, rounding: .toNearestOrZero) + testRoundingShift(UInt.self, rounding: .toNearestOrAway) + testRoundingShift(UInt.self, rounding: .toNearestOrEven) + testRoundingShift(UInt.self, rounding: .toOdd) + testRoundingShift(UInt.self, rounding: .stochastically) + + if #available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *) { + testRoundingShift(Int128.self, rounding: .down) + testRoundingShift(Int128.self, rounding: .up) + testRoundingShift(Int128.self, rounding: .towardZero) + testRoundingShift(Int128.self, rounding: .awayFromZero) + testRoundingShift(Int128.self, rounding: .toNearestOrUp) + testRoundingShift(Int128.self, rounding: .toNearestOrDown) + testRoundingShift(Int128.self, rounding: .toNearestOrZero) + testRoundingShift(Int128.self, rounding: .toNearestOrAway) + testRoundingShift(Int128.self, rounding: .toNearestOrEven) + testRoundingShift(Int128.self, rounding: .toOdd) + testRoundingShift(Int128.self, rounding: .stochastically) + + testRoundingShift(UInt128.self, rounding: .down) + testRoundingShift(UInt128.self, rounding: .up) + testRoundingShift(UInt128.self, rounding: .towardZero) + testRoundingShift(UInt128.self, rounding: .awayFromZero) + testRoundingShift(UInt128.self, rounding: .toNearestOrUp) + testRoundingShift(UInt128.self, rounding: .toNearestOrDown) + testRoundingShift(UInt128.self, rounding: .toNearestOrZero) + testRoundingShift(UInt128.self, rounding: .toNearestOrAway) + testRoundingShift(UInt128.self, rounding: .toNearestOrEven) + testRoundingShift(UInt128.self, rounding: .toOdd) + testRoundingShift(UInt128.self, rounding: .stochastically) } - let expected = DoubleWidth(value) << (8 - count) - let difference = sum >= expected ? sum - expected : expected - sum - // Waving my hands slightly instead of giving a precise explanation - // here, the expectation is that difference should be about - // 1/2 sqrt(256). If it's repeatedly bigger than that, we _may_ - // have a problem, but it's OK for this to fail occasionally. - // - // TODO: precise justification of thresholds - if difference > 8 { fails += 1 } - // On the other hand, if we're more than a couple standard deviations - // off, we should flag that. This still isn't _necessarily_ a problem, - // but if you see a repeated failure for a given shift count, that's - // almost surely a real bug. - XCTAssertLessThanOrEqual(difference, 32, - "Accumulated error (\(difference)) was unexpectedly large in \(value).shifted(rightBy: \(count))" + } + + // Stochastic rounding doesn't have a deterministic "expected" answer, + // but we know that the result must be either the floor or the ceiling. + // The above tests ensure that, but that's not a very strong guarantee; + // an implementation could just implement it as self >> count and pass + // that test. + // + // Here we round the _same_ value many times, compute the average, and + // check that it is acceptably close to the exact expected value; simple + // use of any deterministic rounding rule will not achieve this. + func testStochasticAverage(_ value: T) { + var fails = 0 + for count in 1 ... T.bitWidth { + let sum = (0..<256).reduce(into: DoubleWidth.zero) { sum, _ in + let rounded = value.shifted(rightBy: count, rounding: .stochastically) + sum += DoubleWidth(rounded) + } + let expected = DoubleWidth(value) << (8 - count) + let difference = sum >= expected ? sum - expected : expected - sum + // Waving my hands slightly instead of giving a precise explanation + // here, the expectation is that difference should be about + // 1/2 sqrt(256). If it's repeatedly bigger than that, we _may_ + // have a problem, but it's OK for this to fail occasionally. + // + // TODO: precise justification of thresholds + if difference > 8 { fails += 1 } + // On the other hand, if we're more than a couple standard deviations + // off, we should flag that. This still isn't _necessarily_ a problem, + // but if you see a repeated failure for a given shift count, that's + // almost surely a real bug. + XCTAssertLessThanOrEqual(difference, 32, + "Accumulated error (\(difference)) was unexpectedly large in \(value).shifted(rightBy: \(count))" + ) + } + // Threshold chosen so that this is expected to _usually_ pass, but + // it will fail sporadically even with a correct implementation. This is + // not a great fit for CI workflows, sorry. Basically ignore one-off + // failures, but a repeated failure here is an indication that a bug + // exists. + XCTAssertLessThanOrEqual(fails, T.bitWidth/2, + "Accumulated error was large more often than expected for \(value).shifted(rightBy:)" ) } - // Threshold chosen so that this is expected to _usually_ pass, but - // it will fail sporadically even with a correct implementation. This is - // not a great fit for CI workflows, sorry. Basically ignore one-off - // failures, but a repeated failure here is an indication that a bug - // exists. - XCTAssertLessThanOrEqual(fails, T.bitWidth/2, - "Accumulated error was large more often than expected for \(value).shifted(rightBy:)" - ) + + func testStochasticShifts() { + testStochasticAverage(Int8.random(in: .min ... .max)) + testStochasticAverage(Int16.random(in: .min ... .max)) + testStochasticAverage(Int32.random(in: .min ... .max)) + testStochasticAverage(UInt8.random(in: .min ... .max)) + testStochasticAverage(UInt16.random(in: .min ... .max)) + testStochasticAverage(UInt32.random(in: .min ... .max)) + testStochasticAverage(Int64.random(in: .min ... .max)) + testStochasticAverage(UInt64.random(in: .min ... .max)) + if #available(macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2, *) { + testStochasticAverage(Int128.random(in: .min ... .max)) + testStochasticAverage(UInt128.random(in: .min ... .max)) + } + testStochasticAverage(DoubleWidth.random(in: .min ... .max)) + testStochasticAverage(DoubleWidth.random(in: .min ... .max)) + } } - - func testStochasticShifts() { - testStochasticAverage(Int8.random(in: .min ... .max)) - testStochasticAverage(Int16.random(in: .min ... .max)) - testStochasticAverage(Int32.random(in: .min ... .max)) - testStochasticAverage(UInt8.random(in: .min ... .max)) - testStochasticAverage(UInt16.random(in: .min ... .max)) - testStochasticAverage(UInt32.random(in: .min ... .max)) - testStochasticAverage(Int64.random(in: .min ... .max)) - testStochasticAverage(UInt64.random(in: .min ... .max)) - testStochasticAverage(DoubleWidth.random(in: .min ... .max)) - testStochasticAverage(DoubleWidth.random(in: .min ... .max)) - } -}